Timers

Topic 2 of 2 in Browser APIs6 min readBeginnerFree course

Overview

Timers schedule code to run later. The delay is in milliseconds (1000 ms = 1 second).

JavaScript
const id = setTimeout(() => {
  console.log('Two seconds later');
}, 2000);

clearTimeout(id); // cancel it before it runs

setTimeout doesn’t pause your program. It hands the callback to the browser and returns immediately with an id; the rest of your code carries on, and the callback runs when the time is up (see Callbacks and The event loop).

Extra arguments after the delay are passed to the callback: setTimeout(greet, 1000, 'Asha') calls greet('Asha').

Repeating

JavaScript
let seconds = 0;
const timer = setInterval(() => {
  seconds++;
  clock.textContent = `${seconds}s`;
}, 1000);

stopButton.addEventListener('click', () => clearInterval(timer));

Always keep the id of an interval and clear it when you’re done — an interval you forget about runs for as long as the page is open.

Chained setTimeout

An alternative to setInterval is a setTimeout that schedules the next one when it finishes. It guarantees a gap between runs, even if each run takes a while — useful for polling a server:

JavaScript
async function poll() {
  await refreshNotifications();
  setTimeout(poll, 30_000); // next check 30 s after this one finished
}
poll();

The delay is a minimum, not a promise. If the page is busy (see The event loop), the callback runs late. Background tabs also slow timers down.

Browsers typically limit timers in hidden tabs to about once per second, or less. Never use timers to measure time — store Date.now() when you start and compare later:

JavaScript
const start = Date.now();
setInterval(() => {
  const elapsed = Math.floor((Date.now() - start) / 1000);
  clock.textContent = `${elapsed}s`; // stays correct even if a tick is late
}, 1000);

Debouncing

A common pattern: wait until someone stops typing before searching.

JavaScript
let pending;
input.addEventListener('input', () => {
  clearTimeout(pending);
  pending = setTimeout(() => search(input.value), 300);
});

Keystrokes j, a, v, a arrive quickly; each one cancels the previous 300 ms timer. After the last a there’s a pause, so its timer finishes and search(‘java’) runs. Later, s starts a new timer that finishes and runs search(‘javas’).

Every keystroke cancels the previous timer and starts a new one. Only when the person pauses for 300 ms does a timer survive long enough to run. Instead of one request per keystroke, you send one per pause — far kinder to your server.

As a reusable helper:

JavaScript
function debounce(fn, ms) {
  let id;
  return (...args) => {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), ms);
  };
}

input.addEventListener('input', debounce((e) => search(e.target.value), 300));
window.addEventListener('resize', debounce(updateLayout, 150));

Throttling

Throttling is the cousin of debouncing: it runs at most once every so often, during the activity rather than after it. Use it for things like updating a progress indicator while scrolling:

JavaScript
function throttle(fn, ms) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= ms) {
      last = now;
      fn(...args);
    }
  };
}

window.addEventListener('scroll', throttle(updateProgressBar, 100));
Debounce Throttle
Runs once, after activity stops regularly, during activity
Good for search boxes, saving drafts, resize scroll effects, mouse tracking

Smooth animation

For anything that moves, use requestAnimationFrame. It runs just before the browser draws each frame:

JavaScript
function step(time) {
  box.style.transform = `translateX(${Math.sin(time / 500) * 100}px)`;
  requestAnimationFrame(step);
}
requestAnimationFrame(step);

Why not setInterval(…, 16)? requestAnimationFrame matches the screen’s refresh rate exactly (60, 120 Hz or more), never runs mid-frame, and pauses automatically in background tabs to save battery. The time argument tells you how long the page has been running, so you can base movement on time rather than frame count. Cancel it with cancelAnimationFrame(id).

For many simple animations — fades, slides, hover effects — CSS transitions and animations are easier still. Reach for requestAnimationFrame when the movement depends on calculations.

Waiting with promises

JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

await wait(500);

This makes step-by-step sequences easy to read:

JavaScript
async function showToast(message) {
  toast.textContent = message;
  toast.hidden = false;
  await wait(3000);
  toast.hidden = true;
}
Exercise

A countdown

Write countdown(n) that logs n, n-1, … 1 once per second, then logs 'Go!' and stops. Bonus — return a function that cancels the countdown early.

JavaScript
function countdown(n) {
  // your code here
}

Summary

  • setTimeout runs code once after a delay; setInterval repeats it.
  • Both return an id you can pass to clearTimeout / clearInterval.
  • Delays are minimums: busy pages and background tabs make timers late.
  • Debounce to wait until activity stops; throttle to limit how often something runs.
  • Use requestAnimationFrame for smooth animation.