Middle
let i = 0; function increment() { i++; console.log(i) } function debounce(func, wait = 0) {} const debouncedIncrement = debounce(increment, 100); debouncedIncrement(); // i = 0 debouncedIncrement(); // i = 0 debouncedIncrement(); // i = 0 debouncedIncrement(); // i = 0 debouncedIncrement(); // i = 0 debouncedIncrement(); // i = 0 debouncedIncrement(); // i = 1 setTimeout(debouncedIncrement, 150); // i = 2 setTimeout(debouncedIncrement, 200); // i = 2 setTimeout(debouncedIncrement, 350); // i = 3
sobes.tech AI
Answer from AI
The debounce function is used to limit the frequency of calling the provided func. In this case, debouncedIncrement should call increment no more often than once every 100 ms, and when multiple calls occur in succession, it should only execute increment once after the calls stop for 100 ms.
The debounce implementation can look like this:
function debounce(func, wait = 0) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
Explanation:
- Each time the returned function is called, the previous timeout is cleared.
- A new timeout is set for
waitmilliseconds. - If calls happen in quick succession, faster than
wait, the functionfuncis not called. - Once calls stop for
waitms,funcis called once.
In your example:
- The first few calls to
debouncedIncrement()happen in succession and do not immediately callincrement. - After a pause of 100 ms,
incrementis called and increasesi. - The timeouts with delays of 150, 200, and 350 ms demonstrate that calls close in time are combined, while calls with longer delays trigger
incrementseparately.
This is a classic debounce implementation for controlling the frequency of function calls, for example, during input or scroll events.