javascript - 在不存在的时间间隔上调用clearInterval() 会有什么后果吗?

标签 javascript

我正在使用 javascript 的 setInterval() 函数检查某些设备的连接状态,该函数每 5 秒轮询一次。当这些设备因任何原因需要删除或重新启动时,我将调用 clearInterval() 来停止间隔,然后在设备再次重新启动时开始另一个间隔。

有时,当一开始就没有间隔时,会调用 clearInterval() 函数。例如,我们可以完全禁用状态检查,这样 setInterval() 永远不会被调用。但是,当设备重新启动时,clearInterval()(存在于代码库的不同区域)仍然会触发。它的参数将为 null 或未定义。

我的问题是 - 以这种方式使用 clearInterval() 会产生什么后果吗?您可以继续使用不存在的参数调用该函数而不产生不利影响吗?

最佳答案

正如 @CertainPerformance 已经提到的,就你而言,没有什么坏处。

但这些调用需要花费多少时间仍然很有趣:

const invocations = 1000000;
const d1 = new Date().getTime();
console.log(d1);
for (var i = 0; i < invocations; i++) {
  clearInterval();
}
const d2 = new Date().getTime();
console.log(d2);
console.log(invocations, 'invocations took', d2 - d1, 'millisecs');

关于javascript - 在不存在的时间间隔上调用clearInterval() 会有什么后果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66262640/

相关文章:

javascript - 将对象转换为数组的最佳方法

javascript - 如何在选项卡容器中添加多个 php 网格,每个选项卡一个 phpgrid?

javascript - jQuery:如果每个 tr 都有类,则运行函数

javascript - 使用 Typescript 的 Redux Thunk

javascript - 如何在 javascript 中设置数据 ID?

javascript - 如何在 Angular 2/4/5 中使用 PDF.js?

javascript - 动态表单无法正确插入 MySQL 数据库

javascript - 为什么我的 $watch 只触发一次?

javascript - 如何将 CSS 类应用于刚刚成功的 ID

javascript - Angular 2 模板约定