Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 156 ยท Asynchronous JavaScript

setTimeout and setInterval

Schedule code with setTimeout and setInterval, cancel timers, understand timer accuracy, and build debounce and throttle helpers for busy events.

Timers let you run code later: hide a notification after three seconds, update a clock every second, wait until someone stops typing before searching. JavaScript has two timer functions, setTimeout() for "once, after a delay" and setInterval() for "repeatedly, every so often", plus a matching function to cancel each.

Timers are the simplest asynchronous tool, which makes them the perfect place to practice the event loop ideas from the previous lesson. In this lesson you'll schedule and cancel timers, learn why they're never perfectly on time, and build two helpers that every front-end developer uses sooner or later: debounce and throttle.

setTimeout: run once, later

setTimeout() takes a function and a delay in milliseconds. It returns immediately, and the browser calls your function once the delay has passed:

JS Your first timers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both "Ordering" and "Meanwhile" print first: setTimeout() doesn't pause your program, it just schedules the callback. The callbacks then run in order of their delays, not the order you wrote them.

A few details about the arguments:

  • The delay is optional and defaults to 0. Anything negative or invalid also counts as 0.
  • Extra arguments after the delay are passed to your function: setTimeout(greet, 1000, "Ana") calls greet("Ana").
  • Pass a function, not a call. setTimeout(save(), 1000) calls save immediately and schedules its return value. Write setTimeout(save, 1000) or setTimeout(() => save(), 1000).
  • You can pass a string of code instead of a function, but don't: it works like eval(), and it's blocked by many security policies.

Cancelling with clearTimeout

setTimeout() returns a timer ID. Pass it to clearTimeout() to cancel the timer before it fires. Cancelling a timer that already ran, or passing an invalid ID, is harmless.

JS Cancel a timer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In browsers the ID is a positive integer. In Node.js it's a Timeout object instead. Either way, treat it as an opaque value: store it, and hand it back to clearTimeout().

setInterval: run repeatedly

setInterval() has the same signature, but it keeps calling your function every delay milliseconds until you stop it with clearInterval(). Forgetting to stop an interval is a classic bug: it keeps running (and using memory and battery) forever.

JS A countdown with setInterval

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The callback can stop its own interval, as above, as long as it can see the ID. Here the countdown variable is in the outer scope, so a closure gives the callback access to it.

Chained setTimeout instead of setInterval

You can also repeat work by having a setTimeout callback schedule the next setTimeout. This is often the better choice:

JavaScript
function poll() {
  checkForMessages();
  setTimeout(poll, 5000); // schedule the next run after this one finishes
}
setTimeout(poll, 5000);

The difference is subtle but important. setInterval schedules runs on a fixed rhythm, no matter how long each run takes. A chained setTimeout waits for the full delay after each run finishes, so runs can never pile up, and you can easily change the delay each time (for example, backing off when a server is slow).

Timers are never exact

A timer's delay is a minimum, not a promise. The callback becomes eligible to run after the delay, then waits in the task queue until the call stack is empty. Several things can make it later:

  • Busy code. If other JavaScript is running, the timer waits for it to finish. That's the run-to-completion rule.
  • Nesting. Once timers are nested five levels deep (a timer that sets a timer that sets a timerโ€ฆ), browsers enforce at least 4 ms per delay, even if you asked for 0.
  • Background tabs. Browsers slow timers in hidden tabs to save power, typically to once per second or less.
  • Device sleep and power saving. A laptop lid closing pauses everything.

You can watch the nesting rule kick in by measuring a chain of zero-delay timers:

JS Measuring timer delays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first few gaps are usually well under a millisecond; after about level five they jump to roughly 4 ms. Exact numbers vary by browser and machine.

The practical lesson: never use timers to keep accurate time. A stopwatch that adds 1 to a counter every setInterval(โ€ฆ, 1000) slowly drifts. Instead, record the start time and compute elapsed time from the clock on every tick:

JavaScript
const startedAt = Date.now();
setInterval(() => {
  const elapsed = Math.floor((Date.now() - startedAt) / 1000);
  display.textContent = `${elapsed} s`; // always correct, even if a tick was late
}, 250);

One more limit: the delay is stored as a 32-bit signed integer, so the largest delay is 2,147,483,647 ms, about 24.8 days. Larger values overflow and the timer fires almost immediately.

For smooth animations, use requestAnimationFrame() instead of timers; it's synced with the screen's refresh rate.

Debouncing: wait until things calm down

Some events fire in rapid bursts: input on every keystroke, resize many times per second while a window is dragged. Reacting to every single one can be wasteful, for example sending a search request for "j", "ja", "jav" and "java".

A debounced function waits until the calls stop for a given time, then runs once with the latest arguments. Every new call cancels the pending timer and starts a fresh one:

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

debounce is a higher-order function: it takes a function and returns a new, debounced version. The timerId lives on in the closure between calls. Type in the box below, quickly and then slowly, and compare the two counters:

Debounced search box

Typing "keyboard" quickly fires eight input events but sends only one search, 400 ms after you stop.

Throttling: at most once per interval

Throttling is debouncing's sibling. Instead of waiting for quiet, a throttled function runs at most once per time window, no matter how often it's called. That suits continuous activity where you want regular updates during the burst, such as tracking the pointer or the scroll position.

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

Move your pointer around the box. The raw counter climbs fast; the throttled one updates at most five times per second:

Throttled pointer tracking

This simple throttle drops the final call of a burst, so the last position shown may be slightly out of date. Production-grade versions (such as the ones in utility libraries) add a trailing call to fix that. How to choose:

  • Debounce when only the final value matters: search boxes, autosave, validating a field, recalculating layout after a resize ends.
  • Throttle when you need steady updates during the activity: scroll-position indicators, drag handling, rate-limiting a button.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does setTimeout(save(), 1000) do?

    The parentheses call save right away. Pass the function itself, setTimeout(save, 1000), to call it later.
  2. 2. How do you stop an interval created with const id = setInterval(tick, 1000)?

    Pass the ID that setInterval returned to clearInterval.
  3. 3. A timer is set for 100 ms, but the callback runs after 340 ms. What is the most likely reason?

    The delay is a minimum; the callback runs only when the call stack is free.
  4. 4. You want to send an autosave request only after the user stops typing for one second. Which technique fits?

    Debouncing waits for a pause in the calls and then runs once, which is exactly "after the user stops typing".

Summary

  • setTimeout(fn, ms, ...args) runs a function once after at least ms milliseconds; setInterval repeats it.
  • Both return an ID; cancel with clearTimeout(id) or clearInterval(id). Always stop intervals you no longer need.
  • Pass a function, not a function call, and never a string of code.
  • Delays are minimums: busy code, nesting, background tabs and sleep make timers late, so compute elapsed time from the clock.
  • Chained setTimeout calls can't pile up and can change their delay each time.
  • Debounce runs once after activity stops; throttle runs at most once per interval during activity.

Next: Asynchronous Callbacks โ€” the original way to handle "do this when that finishes", and its pitfalls.