删除对象时杀死setInterval

时间:2012-09-06 19:18:32

标签: javascript

我有以下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将停止被调用

2 个答案:

答案 0 :(得分:2)

你会想要使用getter / setter,Mozilla has some good docs

您可能需要稍微调整一下:

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); 

我对此进行了测试,并确认其有效。

答案 1 :(得分:1)

this小提琴:

// 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);
});
​