</>
Skip to content
JavaScript lessons (60/64)

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));
DebounceThrottle
Firesafter quiet periodmax once per interval
Use casesearch input, resize endscroll 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

  1. Timeout + cancellation before it fires.
  2. 5→1 countdown that clears itself.
  3. Measure any function with performance.now().
  4. Build debounce from scratch; test on an input.
  5. Build throttle; log scroll positions it skips.
  6. 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.