删除对象时终止setInterval
Killing setInterval upon object deletion
我有以下HTML页面:
<html>
<script>
var global = {};
global.obj = {
// when called this function will cause 'hello' to be output to the
// console every 1 second
repeat: function () {
setInterval(function () {
console.log('hello');
}, 1000);
}
}
global.obj.repeat();
global.obj = [];
// even after we overwrite global.obj, 'hello'
// continues to be output to the console every second
</script>
</html>
我想写一个类似于repeat的函数,只是当global.obj被覆盖时,setInterval将停止被调用
你会想要使用getters/ssetters,Mozilla有一些关于这方面的好文档。
你可能需要稍微调整一下:
var intervalRef = null;
var global = {objRef: {}};
global.__defineSetter__("obj", function(o) {
if (intervalRef)
clearInterval(intervalRef);
intervalRef = null;
global.objRef = o;
});
global.__defineGetter__("obj", function() {
return global.objRef;
});
global.obj = {
repeat: function () {
intervalRef = setInterval(function () {
console.log('hello');
}, 1000);
}
}
global.obj.repeat();
setTimeout(function() { //this just demonstrates that you can let it run for 5 secs before clearing the timer.
global.obj = [];
}, 5000);
我对此进行了测试,并验证了它的有效性。
查看此Fiddle:
// html
<p id="stopper">Click</p>
// js
var counter = new Object();
counter.timer = setInterval( function(){
console.log("Hello!");
}, 1000 );
$("#stopper").click(function(){
console.log("Stopping");
clearInterval(counter.timer);
});
相关文章:
- node.js:setInterval()正在跳过调用
- 当使用Watchify时,Browserify+Babelify Gulp任务没有终止
- setInterval和clearInterval javascript无法按需工作
- Eloquent JavaScript递归示例如何终止为返回1,但仍然输出指数值
- Don'我不明白为什么我的setInterval+jQuery;不起作用
- setInterval游戏循环的范围问题
- JavaScript setInterval problems
- 如何在Javascript中延迟setInterval
- 如何执行相同的setInterval()
- SetInterval在javascript对象中表现怪异
- 从setInterval方法移动到带有sprite的requestAnimationFrame
- 如何在悬停时暂停setInterval
- 可以't获取setInterval函数以使用javascript中的this.function_name调用另一
- 删除对象时终止setInterval
- 使用setInterval()函数进行图像闪烁
- “;对于“;内部”;setInterval”;
- 在setInterval函数之前声明时未定义对象
- 使setInterval和setTimeout工作时出现问题
- 事件循环的MEAN.JS setInterval进程(从另一个服务器获取数据)
- 使用setInterval调用原型函数时出现问题