Implement Throttling in JavaScript | Walmart Frontend Interview Question
@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 Throttling. It is way to minimise function calls.

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

To throttle a function means to ensure that the function is called at most once in a specified time period (for instance, once every 10 seconds). This means throttling will prevent a function from running if it has run “recently”. Throttling also ensures a function is run regularly at a fixed rate.

Here is an example.

Before throttling we have a series of calling like

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

After throttling at wait time of 3 dashes

─A─ ─ ─C─ ─ ─D ─ ─ ─ ─ E─ ─ ─G

Testing would look like:

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

throttled();
throttled();
throttled();

clock.tick(04); // increasing clock by 4 seconds
assert.equal(callback.callCount, 1);

throttled();
throttled();
throttled();

clock.tick(04); // increasing clock by 4 seconds
assert.equal(callback.callCount, 2);

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

Loading IDE...

https://www.devtools.tech/