Implement Debounce Function | Flipkart UI - JavaScript Interview Questions
@Yomesh Gupta

In many interviews, Interviewers often ask questions related to web performance. It is an important domain when it comes to large scale web applications. One way to improve performance is to use Debouncing. It is way to minimise function calls.

You have to implement debounce(func, delay) that will return a debounced function, which delays the invoke.

The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called

Here is an example.

Before debouncing we have a series of calling like

─A─B─C─ ─D─ ─ ─ ─ ─ ─E─ ─F─G

After debouncing at wait time of 3 dashes

─ ─ ─ ─ ─ ─ ─ ─ D ─ ─ ─ ─ ─ ─ ─ ─ ─ G

Testing would look like:

var callback = function() { ... };
var throttled = debounce(callback, 3);

for (let i = 0; i < 5; i++) {
  throttled();
}

assert.equal(callback.calledOnce, true);

Callback should be called only once. Don't worry about calledOnce property. That is on us.

Loading IDE...

https://www.devtools.tech/