Debouncing In Javascript
Optimization in Javascript that you should know
What is an Optimization?
Optimization as a generic term is used to define the betterment of a part of the process that will lead to the betterment of the overall process.
What is the concept of debouncing?
These are two concepts that will basically be used in js to enhance the performance of the application by limiting the actions performed in a given interval of time.
Debouncing
It’s the concept in which events are limited by the time means in this the limiting factor is time means only one interval will be fired in the given interval. Example: In an interval of 3 sec only 1 action will be fired.
// debounce.js
let ref;
export const debounce = (fn,timeout=3000) => {
clearTimeout(ref);
ref = setTimeout(() => fn(),timeout)
}
The Above function is the debounce function in which what we basically do is provide it with a function reference and the timeout interval (optional) and what the function does it executes the function using a setTimeout which will lead to the execution of that event after a particular time but before that, it basically clears the previous event by passing ref to the clearTimeout and thus only one event will be triggered at the given interval.
import { debounce } from './debounce.js';debounce(() => console.log('hello')) -> will execute after 3 seconds
debounce(() => console.log('world')) -> will execute after 3 seconds and will cancel the previous event as it's not been 3 seconds since the last event is fired//if i fire the event after 5 seconds
setTimeout(
() => {
debounce(() => console.log('hello after 5 sec'))
}
,5000) -> will execute after and will not be able to cancel the old event as the time has exceeded that is it's been more than 3 seconds//output
world
hello after 5 seconds
The above example has only one problem you can’t make instanced of debouncing means you can’t use it in different files as each debounce instance is using the same reference.
// debounce.js
// modified form of debounce.jsexport const debounce = (fn,timeout=3000) => {
let ref;
return () => {
clearTimeout(ref);
ref = setTimeout(() => fn(),timeout)
}
}
The above example is a modified form or the correct form of debounce function. In this form, each debounce function has a different ref so that it can be used for different functions.
import { debounce } from './debounce.js';const debounceRefFirst = debounce(() => console.log('hello'));
const debounceRefSecond = debounce(() => console.log('world'));debounceRefFirst();
debounceRefFirst();
debounceRefFirst();
debounceRefSecond();
debounceRefSecond();
debounceRefSecond();//output
hello
world
For Example go to
Applications:
The most common applications are listed below
- Analytics (for tooltips mainly on hover actions)
- Limiting API call (Search Bar)
- Generate Report
So that is all I have seen in my cases but I am sure there are many more let me know if find any other interesting use of debouncing.