Javascript 判斷 timeout 是否已經結束
阿新 • • 發佈:2018-11-11
第一個例子,建立包裹函式:
function Timeout(fn, interval) {
var id = setTimeout(fn, interval);
this.cleared = false;
this.clear = function () {
this.cleared = true;
clearTimeout(id);
};
}
使用方法:
var t = new Timeout(function () { alert('this is a test'); }, 5000); console.log(t.cleared); // false t.clear(); console.log(t.cleared); // true
第二個例子,使用prototype:
function Timeout(fn, interval, scope, args) { scope = scope || window; var self = this; var wrap = function(){ self.clear(); fn.apply(scope, args || arguments); } this.id = setTimeout(wrap, interval); } Timeout.prototype.id = null Timeout.prototype.cleared = false; Timeout.prototype.clear = function () { clearTimeout(this.id); this.cleared = true; this.id = null; };
https://stackoverflow.com/questions/5226578/check-if-a-timeout-has-been-cleared/5227508