2

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

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

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

4

1 回答 1

2

正如@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');

于 2021-02-18T15:31:23.037 回答