How to use setTimeout and setInterval in JavaScript

· Category: JavaScript

Short answer

setTimeout runs a function once after a delay, while setInterval repeats it at fixed intervals. Both return an identifier you can pass to clearTimeout or clearInterval to cancel.

Steps

  1. Delay execution: javascript const timer = setTimeout(() => { console.log("Fired after 1 second"); }, 1000);
  2. Repeat execution: javascript const interval = setInterval(() => { console.log("Every 2 seconds"); }, 2000);
  3. Cancel timers: javascript clearTimeout(timer); clearInterval(interval);
  4. Use recursive setTimeout for variable intervals: javascript function tick() { console.log("tick"); setTimeout(tick, Math.random() * 1000); }

Tips

  • Timer delays are not guaranteed; they are minimum delays due to the event loop.
  • Prefer setTimeout recursion over setInterval when task duration may exceed the interval.

Common issues

  • Forgetting to clear intervals causes memory leaks and unwanted background work.
  • this inside timer callbacks defaults to the global object unless bound or using an arrow function.