Explain Codes LogoExplain Codes Logo

'setinterval' vs 'setTimeout'

javascript
timers
async-programming
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 7, 2025
TLDR

setInterval continuously executes a function every X milliseconds:

// Feel like you're caught in a loop? That's the power of setInterval! setInterval(() => console.log('Repeat'), 2000);

setTimeout counters with a single delayed function call, poised after X milliseconds:

// Hang on a sec...or two! Let's delay the next message. setTimeout(() => console.log('Delay'), 2000);

Rein in JavaScript's sense of time by using clearInterval/clearTimeout to halt the scheduled function:

let intervalId = setInterval(...); // Hold your horses, intervalId! Let's stop right there. clearInterval(intervalId);

Mastering timing control

Precision in timing triggers can crafts a more responsive UI or controls timed tasks gracefully. How?

  • Hide a tooltip after a delay? setTimeout got it covered, setting up a one-time action neatly.
  • Coding a clock or refreshing data? Bow to setInterval, tailored for continuous, repeated actions.

Stopping intervals and timeouts is key to prevent draining resources for unneeded processes. User navigated away? Element triggering the timeout or interval is gone? Time to clearInterval or clearTimeout!

Picking the right function

setTimeout and setInterval are like tools in a toolbox. Use the right one for the right problem:

  • Applications needing continuous updates at regular intervals, like clocks or animations? Strap in setInterval.
  • Delaying a singular operation, such as fading a notification after few seconds? setTimeout is your wingman.

The recursive setTimeout secret

Recursive setTimeout mimics setInterval but offers ability to set dynamic delays:

function repeatAction() { console.log('Dynamic Repeat'); setTimeout(repeatAction, 1000); } // Talk about being fashionably late! Delays, your way. setTimeout(repeatAction, 1000);

Dealing with delays

setTimeout and setInterval aren't perfect. Their execution can get delayed by the browser when there is a heavy processing task. It's not about being slow, it's about maintaining system stability!

setInterval could stack calls if your interval time is too short for the function execution, drowning your browser in unending tasks. You don't want to be that kind of program!

Not cleaning up after your intervals and time-outs is also a bad idea. You could end up with "zombie timers", haunting your application (boo!).

Oh, and if your timer function does run into a error? Make sure to catch it with a try-catch block or promise .catch to prevent your applications chaotic downfall!