即使对象已无效,setInterval 函数仍继续运行,我应该先将 setInterval var 更改为 null 还是应该执行其他操作?另外,即使 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);
最佳答案
setInterval 返回的值只是一个数字,用于标识对间隔的引用。您不能只是将其设为 null - 您需要在引用上调用 window.clearInterval。
您发布的代码中还有一些其他内容没有意义。例如,您在函数中声明一个函数,然后只调用它一次。我认为这可能更接近你想要的:
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);
这将运行间隔 5 次。
FWIW,GC 并没有真正参与其中。只要存在对任何变量的引用,就不会收集它。
HTH
关于Javascript:使对象无效时不会删除 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335152/