版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/henryhu712/article/details/83471749
第一个例子,创建包裹函数:
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