javascript - 在clearInterval(id_of_setinterval)之后是否需要将id_of_setinterval变量设置为null?

标签 javascript

var id_of_setinterval = setInterval(function(){}, 2000)

if(id_of_setinterval) {
    clearInterval(id_of_setinterval);
    id_of_setinterval = null; //Does it necessary? Why?
}

我真的不知道为什么要写这段代码。

在我看来,将 id_of_setinterval 设置为 null不必要的。

最佳答案

这取决于。

如果您使用多个计时器并启动和结束某个计时器,那么最好将其设置为零,因为它只保存计时器的 ID,从 setInterval :

The returned timeoutID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to Window.clearInterval() to cancel the timeout.

并且根据clearInterval

It's worth noting that the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably. However, for clarity, you should avoid doing so.

如果只使用一个定时器和一个变量,则无需将 id 设置为零。

关于javascript - 在clearInterval(id_of_setinterval)之后是否需要将id_of_setinterval变量设置为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869259/

相关文章:

Javascript 更改 css top 属性

javascript - 尝试在 Flask 应用程序内提供安全脚本

javascript - 如何使用 jQuery 更新文本区域内的代码

javascript - 使用 jQuery 或其他库的 Apple Cover-flow 效果?

javascript - 如何锁定 Kendo UI Vue Grid 中的列( native )

java - 输入元素的 onclick 内的 document.getelementbyid

javascript - d3js - 创建自定义比例 - 正对数和负对数

javascript - 像在 digital ocean 中一样选择按钮

javascript - 如何将文件 a 移动到 Node.js 中的不同分区或设备?

javascript - 不是函数?