iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Timing

JavaScript has three timing functions: setTimeout, setInterval, and requestAnimationFrame. Each has a niche.

Compare

APIFiresStops with
setTimeout(fn, ms)Once, after ms (or later if main thread is busy)clearTimeout(id)
setInterval(fn, ms)Every ms until clearedclearInterval(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);

Test yourself

Q1. `setTimeout(fn, 0)` runs…
Q2. For frame-paced animation use…
Q3. Cancel a scheduled timeout with…

Discussion

Loading…