Lodash Throttle: Leading vs Trailing Explained

The _.throttle method in the Lodash JavaScript library limits how frequently a function can execute over time. By default, a throttled function can invoke at the start of the wait period, the end of the wait period, or both. This behavior is controlled by two boolean options: leading and trailing. Understanding the difference between these two settings allows developers to optimize event listeners—such as window resizing, scrolling, or button clicks—to execute exactly when desired.

Understanding the Throttle Mechanism

When you wrap a function with _.throttle(fn, wait, options), Lodash creates a cooldown window defined by the wait duration in milliseconds.

_.throttle(func, [wait=0], [options={}])

The options object accepts:

The leading Option

The leading option dictates whether the throttled function executes on the very first trigger before the cooldown interval begins.

The trailing Option

The trailing option dictates whether the function executes one final time after the cooldown period expires, provided the function was called again during that interval.

Behavior Combinations

1. { leading: true, trailing: true } (Default)

The function runs immediately upon the first trigger. If additional triggers happen during the wait duration, the function runs once more at the end of the interval with the latest arguments.

2. { leading: true, trailing: false }

The function runs immediately upon the first trigger, but any subsequent triggers during the wait period are completely discarded. The function will not fire again until the wait duration expires and a new event occurs.

3. { leading: false, trailing: true }

The function does not run immediately when the event starts. Instead, it waits for the duration to elapse and then runs using the most recent event data.

4. { leading: false, trailing: false }

Setting both options to false disables execution entirely. Lodash requires at least one option to be true for the throttled function to invoke; setting both to false creates a no-op function that will never execute.