首页 > 解决方案 > Prevent Multiple Instances for SetInterval

问题描述

What is the most recommended/best way to stop multiple instances of a setInterval function from being created (in javascript) and call it only once?

标签: javascriptnode.js

解决方案


setInterval返回一个间隔 id,您可以使用它来检查它是否已经被实例化。例如:

let intervalId

const someFunction = () => {
  intervalId = setInterval(someOtherFunction, 1000)
}

const someThirdFunction () => {
  if (!intervalId) {
    intervalId = setInterval(someOtherFunction, 1000)
  }
}

推荐阅读