Hello! Welcome to the final lesson in our module on Advanced Asynchronous Patterns.
In our last lesson, we mastered the debounce technique, which is perfect for delaying function execution until a burst of events, like typing in a search bar, has paused. We learned to implement it from scratch using closures and timers.
Today, we'll tackle a related but distinct rate-limiting pattern. Our goal is to implement a throttle function for rate-limiting asynchronous event handlers. While debouncing waits for silence, throttling imposes a strict limit, ensuring a function is never called more than once per specified interval. This is ideal for handling continuous event streams, like scrolling or resizing, where you want regular updates without overwhelming the system.
1. What is Throttling?
Imagine you're implementing an "infinite scroll" feature. As the user scrolls down the page, you need to check their position to see if you should fetch more content. The scroll event can fire dozens of times per second. Making an API call on every single event would be incredibly wasteful and could easily overload your server.
This is where throttling comes in. It allows you to say, "No matter how many times this event fires, I only want to run my function at most once every 300 milliseconds."
Let's watch a brief clip that illustrates this exact scenario.
Javascript Interview Questions ( Debouncing and Throttling ) - Implementation, Examples etc
This video from RoadsideCoder uses the example of Twitter's infinite scroll to explain the core idea behind throttling. Notice how it's not about waiting for a pause, but about enforcing a regular interval between executions.
Watch the segment from 02:10 to 04:53. The presenter explains what throttling is and how it works in a real-world context.
The key idea is to create a "cooldown" period after each execution. Any calls that happen during this cooldown are simply ignored.

2. Implementing a Basic throttle Function
Now, let's build our own throttle function. Like debounce, it's a higher-order function that wraps our target function with rate-limiting logic. The core mechanism, however, is different. Instead of resetting a timer, we'll track the timestamp of the last execution.
The logic works like this:
- When the throttled function is first called, it executes immediately. We record the time of this execution.
- On subsequent calls, we check the current time against the last execution time.
- If enough time has passed (i.e., the specified delay is over), we allow the function to execute and update the last execution time.
- If not enough time has passed, we do nothing.
This implementation is often called a "leading-edge" throttle because the first call in a series is executed immediately.
Let's watch a walkthrough of this implementation.
Javascript Interview Questions ( Debouncing and Throttling ) - Implementation, Examples etc
The same video from RoadsideCoder also provides a great from-scratch implementation of a throttle function. This will solidify the timestamp-based logic.
Watch the section from 15:50 to 19:49, where the host builds a custom myThrottle function.
Here is the code, which should look familiar after watching the video. It relies on a closure to maintain the last timestamp across calls.
function throttle(func, delay) {
// `last` is kept in the closure's scope, acting as our state.
let last = 0;
return function(...args) {
const context = this;
const now = new Date().getTime();
// Check if the difference between now and the last execution
// is greater than the specified delay.
if (now - last < delay) {
// Not enough time has passed, so we do nothing.
return;
}
// Enough time has passed. Update the last execution time...
last = now;
// ...and execute the original function.
func.apply(context, args);
};
}
// --- Usage Example ---
// Function to run on scroll
const handleScroll = () => {
console.log('Fetching data for infinite scroll...');
};
// Create the throttled version of our function.
const throttledHandleScroll = throttle(handleScroll, 1000); // Max once per second
window.addEventListener('scroll', throttledHandleScroll);
Test your understanding!
Imagine you call throttledHandleScroll() at T=0ms, T=500ms, T=1200ms, and T=1800ms with a delay of 1000ms. At which timestamps will the console.log message actually appear?
Show answer
The message will appear at T=0ms and T=1200ms.
T=0ms: The first call runs immediately because0 - 0 < 1000is false.lastbecomes0.T=500ms:500 - 0 < 1000is true. The call is ignored.T=1200ms:1200 - 0 < 1000is false. The function runs.lastbecomes1200.T=1800ms:1800 - 1200 < 1000is true (600 < 1000). The call is ignored.
3. Advanced Throttling: Leading and Trailing Edges
The simple implementation we just built is great, but it has a limitation. If the user stops scrolling right after a call was ignored, that final event is lost. Sometimes, you want to ensure the last action in a series also gets processed. This is handled by adding a trailing-edge call.
Production-grade throttle functions, like the one in Lodash, often provide options to control this behavior.
implement throttle() with leading & trailing option
This problem description from BigFrontend.dev clearly explains the concepts of 'leading' and 'trailing' options, which control whether the function fires at the beginning or end of the waiting period.
Read the problem description and the 'Explanation' section. The timeline diagrams do an excellent job of visualizing how the {leading: boolean, trailing: boolean} options change the function's execution pattern.
To implement a trailing option, we need to combine our timestamp logic with the timer logic from debounce.
- If a call is made but ignored (because it's within the cooldown period), we set a
setTimeout. - This timer will execute the function after the
delayperiod has finished, effectively handling the "trailing" call. - We also need to make sure we don't set multiple redundant timers.
Here’s how a more robust throttle function with leading (the default) and trailing options could look:
function throttleWithTrailing(func, delay, options = { leading: true, trailing: true }) {
let last = 0;
let timerId = null;
let lastArgs = null;
let lastThis = null;
// The function that gets executed by the timer
function trailingCall() {
last = options.leading ? new Date().getTime() : 0;
timerId = null;
func.apply(lastThis, lastArgs);
}
return function(...args) {
const now = new Date().getTime();
// Handle the very first call when leading is disabled
if (!last && !options.leading) {
last = now;
}
const remaining = delay - (now - last);
lastArgs = args;
lastThis = this;
if (remaining <= 0 || remaining > delay) {
// We can execute now
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
last = now;
if (options.leading) {
func.apply(lastThis, lastArgs);
}
} else if (!timerId && options.trailing) {
// We're in the cooldown period, so schedule a trailing call
timerId = setTimeout(trailingCall, remaining);
}
};
}
This implementation is significantly more complex, but it highlights the kind of robust logic required for a general-purpose utility. It manages both immediate execution (leading) and ensures the last pending call is not lost (trailing).
4. Throttling Asynchronous Functions in Practice
While our handmade functions work for async operations, production environments often use specialized libraries for throttling promises and async functions. These libraries offer more features, like queuing calls instead of dropping them.
A great example is p-throttle. It's designed specifically for rate-limiting interactions with external APIs, where you can't afford to lose calls.
The p-throttle library on GitHub is an excellent example of a production-ready async throttling utility. Its documentation showcases features that go beyond a simple delay.
Read the initial description to understand its purpose (queuing vs. dropping calls). Look at the 'Usage' example to see how it works with async functions. Then, review the 'API' section for the limit and interval options, and finally, look at the throttledFn.queueSize property for an advanced use-case.
Key features of p-throttle that are relevant to your goals include:
- Queueing: Instead of ignoring calls, it queues them to run as soon as the rate limit allows. This is crucial for API interactions where every call must eventually complete.
- Complex Rate Limits: It allows you to specify a
limitof calls perinterval(e.g., 100 calls per minute), which is more flexible than a simple delay. - Queue Management: You can inspect
queueSizeto implement fallback logic, like using a different, less precise data source if the primary API queue is too long. This is a practical pattern in robust system design.
Debounce vs. Throttle: The Final Showdown
You've now implemented both debounce and throttle. Let's end with a clear visual summary.

When to use which:
- Use
debouncewhen you only care about the final state. Think "wait for the user to finish what they're doing."- Examples: Search bar suggestions, form validation, saving changes in an auto-save editor.
- Use
throttlewhen you need to handle events as they happen, but at a controlled rate. Think "fire continuously, but don't overwhelm me."- Examples: Infinite scrolling, tracking mouse movement, responsive resizing calculations that must update during the resize.
Conclusion
Congratulations on completing this module on advanced asynchronous patterns! You've moved beyond simple promises and async/await to control the flow and rate of asynchronous operations—a critical skill for building high-performance applications.
Key Takeaways:
- Throttling limits a function's execution to at most once per specified interval, ignoring calls that come too quickly.
- It's essential for performance with high-frequency events like
scroll,resize, andmousemove. - A basic implementation uses a timestamp within a closure to track the last execution time.
- Advanced implementations can handle
leadingandtrailingedge calls, providing more control over when the function fires. - For promise-based and async operations, libraries like
p-throttleoffer robust queuing and rate-limiting features essential for API interactions.
Next Up
We're about to shift gears dramatically. We've been focused on how and when functions are called. In the next module, Metaprogramming with Proxies and Reflect, we'll explore how to fundamentally change the behavior of JavaScript objects themselves. We'll start by creating a Proxy to intercept and customize basic operations like getting or setting a property, opening up a whole new world of dynamic programming possibilities.