Skip to main content

Debouncing and Throttling in JavaScript (Live Playground)

In this tutorial, we will explore debouncing and throttling in JavaScript. These techniques can help improve the performance of your web applications by controlling the rate at which events are executed.

Debouncing

Debouncing is a technique that delays the execution of a function until a specified period of time has passed since the last time it was invoked. It is useful when you want to limit the rate of function calls, for example, when handling events like scrolling, resizing, or user input.

Debouncing Example

In the example below, we create a debounce function that takes a function and a delay as arguments and returns a new function that will only be executed after the specified delay has passed since its last invocation.

function debounce(func, delay) {
let timeout;

return function () {
const context = this;
const args = arguments;

clearTimeout(timeout);

timeout = setTimeout(function () {
func.apply(context, args);
}, delay);
};
}

// Usage
const debouncedFunction = debounce(function () {
console.log('Function called after 300ms');
}, 300);

window.addEventListener('click', debouncedFunction);
Live Playground, Try it Yourself

Throttling

Throttling is a technique that ensures a function is executed at a fixed rate, no matter how many times it is invoked. This is useful when you want to limit the number of times a function is called in a given time period, for example, when handling events like scrolling, resizing, or user input.

Throttling Example

In the example below, we create a throttle function that takes a function and a delay as arguments and returns a new function that will only be executed at most once every specified delay.

function throttle(func, delay) {
let lastCall = 0;

return function () {
const context = this;
const args = arguments;
const now = new Date().getTime();

if (now - lastCall >= delay) {
lastCall = now;
func.apply(context, args);
}
};
}

// Usage
const throttledFunction = throttle(function () {
console.log('Function called at most every 300ms');
}, 300);

window.addEventListener('click', throttledFunction);
Live Playground, Try it Yourself

Conclusion

Debouncing and throttling are powerful techniques in JavaScript that can help you improve the performance of your web applications. By understanding how to implement these techniques, you can better optimize your code to handle events more efficiently and provide a smoother user experience.