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

JavaScriptAll Levels
1165
Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.

InternationalDomestic

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...