Debouncing is a technique used to control how many times we allow a function to be executed over time. When a JavaScript function is debounced with a wait time of X milliseconds, it must wait until after X milliseconds have elapsed since the debounced function was last called.
You almost certainly have encountered debouncing in your daily lives before (e.g. when entering an elevator). Only after X duration of not pressing the "Door open" button (the debounced function not being called) will the elevator door close.
Use a closure to retain the latest timerId. On every call, clear the previous timeout and schedule a new one so the wrapped function only fires once activity has settled.
20if (timerId === null) {21return;22}23clearTimeout(timerId);24fnArgs = null;25thisArgs = null;26};2728debounced.flush = function () {29if (timerId === null) {30return;31}32clearTimeout(timerId);33func.call(thisArgs, ...fnArgs);34};35return debounced;36}