当线程通过clearInterval被杀死时,有没有办法执行某些代码?

时间:2012-01-11 23:35:03

标签: javascript

对于通过setInterval运行的特定线程,是否存在类似“dispose”函数或“thread shutdown hook”的内容?

2 个答案:

答案 0 :(得分:2)

(function () {
    var _setInterval = window.setInterval,
        _clearInterval = window.clearInterval;



    window.setInterval = function (fn, time) {
        //Implement your hooks here, hopefully without side effects
        return _setInterval(fn, time);
    };

    window.clearInterval = function (id) {
        //Implement your hooks here, hopefully without side effects
        return _clearInterval(id);
    };

})()

从评论中可以清楚地看到,您不需要挂钩,因为您处于您控制的环境中。在这种情况下,你可以用相同的原理编写像myClearInterval等包装函数。

答案 1 :(得分:1)

首先,正如其他人所说,javascript中没有线程(除了WebWorkers,但我认为这不是你在这里谈论的。

所有setInterval()所做的就是重复调用一个函数 - 它不是一个线程,它不是先发制人的,它不会被调用,直到所有其他的javascript都停止执行所以定时器事件可以处理。如果你的问题是你想要在间隔被清除时处理某些状态以便它不再被调用,那么你有两个选择:

1)您可以使用javascript闭包来存储您的状态,当间隔被清除时,闭包将自动释放。

2)您可以创建自己的clearInterval版本,清除间隔计时器并清理状态。

javascript闭包选项如下所示:

var interval;
function startMyInterval() {
    // sample state variables
    var state1 = 0;
    var state2 = [];
    var state3 = {whatever: "whatever"};

    interval = setInterval(function() {
        // javascript code here that can reference state1, state2 and state3
    }, 1000);
}

// then some time later when you want to stop the interval, you call clearInterval
// the closure is released and all the state variables are freed automatically
clearInterval(interval);

或者,如果你想在清除间隔时做任何其他事情,你可以自己创建一个函数来清除不仅会释放闭包的间隔,还可以让你运行任何其他代码。

function clearMyInterval() {
    clearInterval(interval);
    // do any other cleanup you want to when the interval is stopped
}

我看到其他人建议使用你自己的函数挂钩/替换window.clearInterval(),但我不想这样做,因为不清楚这是否是支持/记录的功能和一些系统功能(越来越多的它们随着时间的推移而变得受到保护,因此它们无法被替换。

相关问题