我正在使用 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/