3

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

4

2 回答 2

2

你会想要使用 getter/setter,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); 

我对此进行了测试并验证了它的工作原理。

于 2012-09-06T19:33:10.773 回答
1

看到这个小提琴:

// 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);
});
​
于 2012-09-06T19:41:42.910 回答