Course contentsShow
← JavaScript
Lesson 2389 of 2,72349. Common Patterns and IdiomsFree lesson

Leading and Trailing Options in Throttle

Control whether throttle fires immediately, at the end of the interval, or both.

Leading and Trailing Options in Throttle

You'll learn how to control whether a throttled function fires immediately on the first call, at the end of the throttle interval, or both.

The Core Idea

When you throttle a function, you might want different behaviors:

  • Leading edge: Fire immediately when called, then ignore calls for the interval duration
  • Trailing edge: Wait until the interval ends, then fire with the last call's arguments
  • Both: Fire immediately and once more at the end if there were additional calls

Think of a subway turnstile. With leading, you pass through immediately, and it locks for a few seconds. With trailing, it waits a moment to see if you're really going, then lets you through. With both, you go through now, but if people kept trying, one more person gets through when the lock resets.

Configuring the Behavior

You extend your throttle function to accept options:

function throttle(fn, delay, { leading = true, trailing = true } = {}) {
  let timeout = null;
  let lastArgs = null;
  let lastCallTime = 0;

  return function(...args) {
    const now = Date.now();
    const timeSinceLastCall = now - lastCallTime;

    if (!lastCallTime && !leading) {
      lastCallTime = now;
    }

    lastArgs = args;

    if (timeSinceLastCall >= delay) {
      if (leading) {
        fn.apply(this, args);
        lastCallTime = now;
      }
    }

    if (trailing && !timeout) {
      timeout = setTimeout(() => {
        fn.apply(this, lastArgs);
        lastCallTime = Date.now();
        timeout = null;
      }, delay - timeSinceLastCall);
    }
  };
}

With { leading: true, trailing: false }, you get instant response. With { leading: false, trailing: true }, you only fire after activity stops within the interval.

Key Takeaway: Leading and trailing options let you fine-tune throttle behavior—firing immediately, after the interval, or both—depending on whether you need instant feedback, delayed batch processing, or comprehensive coverage.