在计时器运行后向JS setTimeout添加持续时间

Jon*_*ine 9 javascript

我正在试图找出一种模拟AS3的Timer类的方法.

如果您不熟悉,可以做的一件很酷的事情就是为计时器添加持续时间,即使它已经在运行.此功能有很多非常好的用途.

有没有人想过在js做这件事?

Fel*_*ing 12

我不熟悉这个类,但您可以轻松地在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);
   }
}
Run Code Online (Sandbox Code Playgroud)

用法:

var timer = new Timer(function() { // init timer with 5 seconds
    alert('foo');
}, 5000);

timer.add(2000); // add two seconds
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 5

清除超时,然后将新超时设置为新的所需结束时间。