删除对象时终止setInterval

Killing setInterval upon object deletion

本文关键字:setInterval 终止 对象 删除      更新时间:2023-09-26

我有以下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);
});
​