在计时器运行后向JS setTimeout添加持续时间 [英] Add duration to JS setTimeout after the timer is running
本文介绍了在计时器运行后向JS setTimeout添加持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在试图找出一种模拟AS3的Timer类的方法。
I'm trying to figure out a way to emulate AS3's Timer class.
如果你不熟悉,你可以做的一件很酷的事情是添加计时器的持续时间,即使它已经运行。此功能有很多非常好的用途。
If you're not familiar, one of the cool things you can do is add duration to the timer even if it's already running. This functionality has a lot of very nice uses.
任何人都有在js中这样做的想法吗?
Anyone have any thoughts on doing this in js?
推荐答案
我不熟悉这个类,但你可以在JavaScript中轻松创建类似的东西:
I'm not familiar with this class, but you can easily create something similar in JavaScript:
function Timer(callback, time) {
this.setTimeout(callback, time);
}
Timer.prototype.setTimeout = function(callback, time) {
var self = this;
if(this.timer) {
clearTimeout(this.timer);
}
this.finished = false;
this.callback = callback;
this.time = time;
this.timer = setTimeout(function() {
self.finished = true;
callback();
}, time);
this.start = Date.now();
}
Timer.prototype.add = function(time) {
if(!this.finished) {
// add time to time left
time = this.time - (Date.now() - this.start) + time;
this.setTimeout(this.callback, time);
}
}
用法:
var timer = new Timer(function() { // init timer with 5 seconds
alert('foo');
}, 5000);
timer.add(2000); // add two seconds
这篇关于在计时器运行后向JS setTimeout添加持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文