CodeBlanks Logo Icon CodeBlanks

Throttle

JavaScript course · Expert · Lesson 10/63

Use throttle to ensure a function runs at most once per interval.

Throttle

Throttle ensures a function runs at most once per time interval. Unlike debounce, it does not wait; it ignores calls until the interval elapses.

For example, instead of handling every pixel of a scroll event, you update once every 100 ms. This keeps performance steady and the experience smooth.

Leading and trailing

Throttle has two common modes. In leading mode the first call runs immediately at the start of the interval; in trailing mode a final call is queued at the end.

Most apps use leading only, but some want both. Choose what fits your needs and keep the behavior consistent.

Exercise Throttle function

Write a function named throttle. It takes fn and interval and returns a wrapper that tracks the last run time with lastRun. Use Date.now() for the current time and call fn when the interval has passed.

Show example solution
Start with lastRun = 0; on each call read Date.now(), run when the condition holds, then set lastRun = now.

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

Test yourself

  1. Throttle condition

    if (now - lastRun >= ____) {
      lastRun = now;
      fn(...args);
    }
    Show answer
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  2. What happens when a throttled function is called rapidly?

    • All calls queue up and the last runs
    • Only the first call runs, rest ignored
    • Calls are ignored until the interval passes
    • Each call runs once
    Show answer

    Calls are ignored until the interval passes — Correct! Throttle ignores calls until the interval has passed.

  3. Match the throttle terms

    interval
    minimum gap
    lastRun
    last execution time
    leading
    first call runs
    trailing
    last call fires

All lessons in Expert