我有一个全局变量
global.loggedInUsers = {};
。此对象用作并且字典被唯一的 key:value
对占用。
键是唯一的,值是一个帐户对象。
function Account(hash, jsonData) {
this.hash = hash;
this.accountJson = JSON.parse(jsonData);
this.pongUpdate = 20;
setInterval(function() {
// Stuff happens here blah blah
}, 1000);
}
Account.protoype....
在我的代码中的某个时刻,我最终调用了删除函数
delete(loggedInUsers.key);
因为 Account
类封装了 setInterval
调用,如果 Account
对象被删除,setInterval 会停止还是我必须存储 setInterval在变量中在析构函数中处理它?</p>
最佳答案
setInterval
中对函数的引用存在,并且由于您没有使用 clearInterval
- 它会继续运行。
var t = 1;
function Account() {
this.a = setInterval(function() {
console.log('a ' + t)
t += 1
}, 1000);
}
a = new Account();
setTimeout(function() {
delete(a)
}, 3000)
请注意,在 javascript
中无法创建 Destructor
函数,因此一旦您删除
对象,您需要确保setInterval
也被清除:
var t = 1;
Account = function() {
this.a = setInterval(function() {
console.log('a ' + t)
t += 1
}, 1000);
}
Account.prototype.clear = function() {
clearInterval(this.a)
}
a = new Account();
setTimeout(function() {
a.clear()
delete(a)
}, 3000)
关于javascript - Javascript 的 setInterval 是否在父对象被销毁时被杀死?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41412463/