CPCODELAB
JavaScript

Timers: setTimeout and setInterval

6 min read

Scheduling Code with Timers

setTimeout runs a callback once after a delay. setInterval runs it repeatedly at a fixed interval. Both return an ID you can pass to the corresponding clear function to cancel.

javascript
// Run once after 2 seconds
const timeoutId = setTimeout(() => {
  console.log("2 seconds later!");
}, 2000);

// Cancel before it fires
clearTimeout(timeoutId);

// Run every 1 second
const intervalId = setInterval(() => {
  console.log("tick");
}, 1000);

// Stop after 5 ticks
let ticks = 0;
const id = setInterval(() => {
  ticks++;
  if (ticks >= 5) clearInterval(id);
  console.log("tick", ticks);
}, 1000);

Timer delays are minimum delays, not guaranteed. If the main thread is busy, the callback will run as soon as it is free. A setTimeout(..., 0) defers a callback to after the current synchronous code finishes — a useful trick to escape the current call stack.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises