Optimizing User Interactions: A Guide to Debouncing and Throttling in JavaScript

sidverma
4 min readJan 14, 2023

Debouncing and throttling are techniques used to limit the number of times a function is called in a given period of time. They are often used in situations where a function is called multiple times in rapid succession, such as when a user is typing into an input field or scrolling on a page.

In other definition:

Debouncing and throttling are techniques used to limit the number of times a function is called in a certain period of time. They are useful for improving the performance of an application and preventing it from becoming unresponsive.

Here’s an example of debouncing in JavaScript:

function debounce(fn, delay) {
let timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}

const debouncedFunction = debounce(() => {
console.log("Function called!");
}, 1000);

// The function will only be called once, even if it's invoked multiple times within a 1 second period.

Explanation:

Here we have a debounce function which takes two arguments, the first one is the function to be debounced and the second is the time delay. Inside the debounce function, we have a timeoutId and an anonymous function which takes no arguments.

The first line inside this function is to clear the timeout using the clearTimeout function and passing timeoutId as an argument. Next, we set the timeout using setTimeout function with delay as the second argument, this function is wrapped inside an anonymous function which calls the original function passed to debounce function with its arguments.

Now we can use this debounced function, in the example provided, it logs “Function called!” to the console only once, even if it’s invoked multiple times within a 1 second period.

Here is an example of throttling in JavaScript:

function throttle(fn, limit) {
let inThrottle = false;
return function() {
if (!inThrottle) {
fn.apply(this, arguments);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}

const throttledFunction = throttle(() => {
console.log("Function called!");
}, 1000);

// The function will be called once per second, even if it's invoked multiple times within that period.

Explanation:

Here we have a throttle function which takes two arguments, the first one is the function to be throttled and the second is the limit of time. Inside the throttle function, we have a variable inThrottle which is initially set to false, this variable is used to check if the function is already called within the limit provided. Next, we have an anonymous function which takes no arguments.

The first line inside this function is to check if inThrottle is false, if it’s true it calls the original function passed to throttle function with its arguments and sets inThrottle to true. Next, it sets a timeout of limit time after which it sets inThrottle to false.

Now we can use this throttled function, in the example provided, it logs “Function called!” to the console once per second, even if it’s invoked multiple times within that period.

Let’s take another example:

function debounce(func, wait) {
let timeout;
return function() {
const context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}

The debounce function takes two arguments: the function to be called and the wait time in milliseconds. Inside the function, we create a timeout variable and return a new function. This new function will clear any existing timeout, and set a new timeout with the provided function and wait time.

Here is an example of how to use the debounce function:

const debouncedFunction = debounce(() => {
console.log('Debounced function called.');
}, 1000);

document.querySelector('#some-button').addEventListener('click', debouncedFunction);

In this example, we create a debounced version of an anonymous function that logs a message to the console. Then, we attach it to a button’s click event. Now, when the button is clicked multiple times within the one-second wait time, the function will only be called once, after the wait time has passed since the last click.

Here is an example of a throttling function in JavaScript:

function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}
}

The throttle function takes two arguments: the function to be called and the limit time in milliseconds. Inside the function, we create a lastFunc and lastRan variable and return a new function. This new function will check if the last call of the function is greater than the limit time and if it’s true it will call the function otherwise it will wait for the remaining time to pass.

Here is an example of how to use the throttle function:

const throttledFunction = throttle(() => {
console.log('Throttled function called.');
}, 1000);

document.querySelector('#some-button').addEventListener('mousemove', throttledFunction);

In this example, we create a throttled version of an anonymous function that logs a message to the console. Then, we attach it to a button’s mousemove event. Now, when the button is hovered multiple times within the one-second limit time, the function will only be called once per second.

It’s worth noting that the above examples of debounce and throttle functions are just one way to implement them and there are multiple ways to implement them, with different variations and trade-offs.

#javascript #throttle #debounce #webperformance #frontendinterview

--

--