github: https://github.com/hpcslag/newTimer.js
程式碼:
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); } } module.exports = Timer;
實際套用:
var Timer = require('./timer.js'); var timer = new Timer(function() { // init timer with defalut(0) seconds console.log("FOO"); }, 0); timer.add(1000);
實際上,就算timer設定為0, 後續有增加時間,timer還是會受到影響。
這樣的腳本實際就可以操作有時間生命週期這種規則的程式。
沒有留言:
張貼留言