当父对象被销毁时,Javascript 的 setInterval 是否被杀死?

Was*_*oth 1 javascript node.js

我有一个全局变量 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....
Run Code Online (Sandbox Code Playgroud)

在我的代码中的某个时刻,我最终调用了删除函数

delete(loggedInUsers.key);
Run Code Online (Sandbox Code Playgroud)

因为Account类包含setInterval调用,如果Account对象被删除, setInterval 会停止还是我必须将 setInterval 存储在变量中,在析构函数中处理它?

Dek*_*kel 5

对函数的引用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)
Run Code Online (Sandbox Code Playgroud)

请注意,javascript无法创建Destructor函数,因此一旦创建了delete对象,您将需要确保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)
Run Code Online (Sandbox Code Playgroud)

  • 只要你没有调用`clearInterval` - 没有明确的。该函数有一个引用(来自当前的“窗口/应用程序”)范围,它将继续运行。 (2认同)