简体   繁体   English

Javascript:使对象无效时不会删除setInterval

[英]Javascript: setInterval isn't removed when nullifying an object

The setInterval function keeps running even though the object is nullified, should I change the setInterval var to null first or should I do something else? 即使对象已无效,setInterval函数仍保持运行,我应该先将setInterval var更改为null还是应该做其他事情? Also, will the GC remove the object even if the setInterval is still running? 另外,即使setInterval仍在运行,GC也会删除对象吗?

Test = function(){
    function start(){
        // setTimout for controllable FPS
        var loop = setInterval(function(){
            console.log("TEST");
        }, 1000);
    }

    start();
};


var test = new Test();

setTimeout(function(){
    console.log("DIE!!");
    test = null;
}, 2000);

JsFiddle JsFiddle

the value returned by setInterval is just a number that used to identify the reference to the interval. setInterval返回的值只是一个数字,用于标识对间隔的引用。 you can't just null it - you need to call window.clearInterval on the reference. 您不能只是将其设为空-您需要在引用上调用window.clearInterval。

there's a few other things that don't make sense in the code you posted. 您发布的代码中还有其他一些没有意义的内容。 for example, you're declaring a function in a function then just calling it once. 例如,您要在函数中声明一个函数,然后只调用一次。 i think this is probably closer to what you want: 我认为这可能更接近您想要的:

var Test = function(){
  this.start();
}
Test.prototype = {
  loop : null,
  start : function(){
    this.loop = window.setInterval(function(){
      console.log('TEST');
    }, 1000);
  },
  stop : function(){
    window.clearInterval(this.loop);
  }
}

var test = new Test();
window.setTimeout(function(){
  test.stop();
}, 5000);

That'll run the interval 5 times. 该间隔将运行5次。

FWIW, the GC isn't really involved here. FWIW,GC并没有真正参与其中。 As long as there's a reference to any variable, it won't be collected. 只要有对任何变量的引用,就不会收集它。

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM