JS Timing
JavaScript has three timing functions: setTimeout, setInterval, and requestAnimationFrame. Each has a niche.
Compare
| API | Fires | Stops with |
|---|---|---|
setTimeout(fn, ms) | Once, after ms (or later if main thread is busy) | clearTimeout(id) |
setInterval(fn, ms) | Every ms until cleared | clearInterval(id) |
requestAnimationFrame(fn) | Before next paint (~60 / 120 Hz) | cancelAnimationFrame(id) |
queueMicrotask(fn) | End of current task, before timers | — |
Basics
JS
const id = setTimeout(() => console.log("later"), 1000);
clearTimeout(id);
const tick = setInterval(() => console.log("tick"), 1000);
clearInterval(tick);
// setTimeout(fn, 0) does NOT run immediately — it queues
console.log("1");
setTimeout(() => console.log("3"), 0);
console.log("2");
// 1, 2, 3
Recursive setTimeout vs. setInterval
JS
// setInterval — fixed cadence, can drift if work takes too long
setInterval(work, 1000);
// Recursive setTimeout — guarantees gap between runs
function loop() {
work();
setTimeout(loop, 1000);
}
setTimeout(loop, 1000);
Promise-based delay
JS
const wait = (ms) => new Promise(r => setTimeout(r, ms));
async function example() {
await wait(500);
console.log("after delay");
}
Tip: For frame-paced animation, use
requestAnimationFrame — it pauses in background tabs (saving battery) and syncs with the display.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Timing!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Run greet() once after one second.
(greet, 1000);
Two words concatenated.
Discussion
Loading…