Javascript 判断 timeout 是否已经结束

第一个例子,创建包裹函数:

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

你可能感兴趣的:(nodejs,Javascript,javascript)