Make a timer in JavaScript

javascript

Updated August 29, 2026

Use setTimeout for one delayed action and setInterval for repeated callbacks:

let remaining = 10;
const id = setInterval(() => {
  console.log(remaining--);
  if (remaining < 0) clearInterval(id);
}, 1000);

Timers schedule callbacks; they do not guarantee exact execution times. A busy main thread or a background tab can delay them. For a countdown, calculate elapsed time from Date.now() on each tick instead of subtracting one and assuming every callback was exactly one second apart.

Always keep the timer ID and clear it when the component or page no longer needs it. In a browser, update visible text with an accessible status and avoid creating multiple intervals after repeated button clicks. In Node, setTimeout and setInterval keep the process active unless cleared or configured otherwise.

Sources

related.

Ruslan Osipov

Ruslan Osipov

About the author