JavaScript — Timing
Scheduled work
setTimeout(() => console.log("Hello"), 1000); // once, after ~1s
const id = setInterval(() => console.log("Tick"), 1000); // repeatedly
Both return an ID for cancellation:
clearTimeout(id);
clearInterval(id);
Timers don't block — and aren't exact
console.log("A");
setTimeout(() => console.log("B"), 1000);
console.log("C");
// A → C → B the callback waits its turn
Even setTimeout(fn, 0) means "when the current work finishes and the event loop allows" — never "instantly." Busy scripts delay timer callbacks arbitrarily.
setInterval likewise promises approximately every N ms, not a guarantee.
Countdown pattern
let count = 5;
const id = setInterval(() => {
console.log(count);
if (--count < 0) clearInterval(id); // stop yourself when done
}, 1000);
Recursive setTimeout vs setInterval
For async/repeating work, self-rescheduling is often safer (no overlapping runs):
function poll() {
setTimeout(async () => {
await checkServer();
poll(); // schedule AFTER work completes
}, 1000);
}
Measuring time
performance.now(); // high-resolution duration measuring
Date.now(); // wall-clock timestamp (ms since epoch)
const start = performance.now();
doWork();
console.log(performance.now() - start, "ms");
Debounce — wait until activity stops
function debounce(fn, delay) {
let id;
return (...args) => {
clearTimeout(id);
id = setTimeout(() => fn(...args), delay);
};
}
input.addEventListener("input", debounce(e => search(e.target.value), 300));
Every keystroke resets the clock; only the pause fires. Essential for search boxes.
Throttle — at most once per window
function throttle(fn, delay) {
let waiting = false;
return (...args) => {
if (waiting) return;
fn(...args);
waiting = true;
setTimeout(() => (waiting = false), delay);
};
}
window.addEventListener("scroll", throttle(updateHeader, 100));
| Debounce | Throttle | |
|---|---|---|
| Fires | after quiet period | max once per interval |
| Use case | search input, resize end | scroll handlers, game loops |
requestAnimationFrame — animation's timer
function animate() {
updateFrame();
const id = requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
cancelAnimationFrame(id);
Synced to display refresh (~60fps), paused in background tabs — strictly better than setInterval drawing.
Mini Practice
- Timeout + cancellation before it fires.
- 5→1 countdown that clears itself.
- Measure any function with performance.now().
- Build debounce from scratch; test on an input.
- Build throttle; log scroll positions it skips.
- rAF square moving across the screen; cancel on click.
Next: cookies →
Related Topics
Frequently Asked Questions about Timing
What is Timing in JavaScript?
Timing is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Timing?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Timing.
Why is Timing important in JavaScript?
Timing is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.