DEV Community

Discussion on: Why you should be careful using setInterval?

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

This isn't so much a problem with setInterval per se as with repeatedly executing (potentially) expensive operations without any supervision.

To prevent this, one could simply build a wrapper like this:

const interval = (callback, timeout) => {
   setTimeout(() => {
      const result = callback()
      if (result && ("then" in result))
         result.then(() => interval(callback, timeout))
      else
         interval(callback, timeout)
   }, timeout)
}
Enter fullscreen mode Exit fullscreen mode

And try it out like this:

interval(() => new Promise(resolve => {
   console.log("Starting...")
   setTimeout(() => {
      console.log("...Finished")
      resolve()
   }, 1e3)
}), 1e3)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rakshit profile image
Rakshit

Yes using nested setTimeout is one way to bypass this. You anyways gotta be careful when you do this. Thanks for sharing :)