Skip to content
Share
Explore

Throttling and Debouncing

Debouncing
Debouncing is a technique where you delay the execution of a function until a certain amount of delay is there between the function trigger.
“Do not run yet. If another call comes, forget this one.”
export default function debounce(func, wait) {
let timerId;

return function (...args) {
const context = this; // I can also do args = arguments (arguments is special keyword and contain all the arguments

clearTimeout(timerId);

timerId = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}

// Debounce - II

export default function debounce(func, wait) {
let timerId, args, self;

function debouncedFunction() {
args = arguments;
self = this;

clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(self, args);
args = null;
}, wait)
}

debouncedFunction.cancel = function() {
clearTimeout(timerId);
args = null;
}

debouncedFunction.flush = function() {
clearTimeout(timerId);
if(args)
func.apply(self, args);
}
return debouncedFunction;
}
Note:
The returned function must be a normal function; otherwise, this context can not be applied.
const obj = {
x: 10,
log() {
console.log(this.x);
}
};

obj.log = debounce(obj.log, 300);
obj.log(); // undefined if arrow function returned by debounce

// works with normal function because when called as a method (e.g., obj.method()), this points to the object.
See how the function being called directly and cancel and flush as object of the function being done. Don’t forget this. Functions are also objects, so we can do this.
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.