Frontend101 logoFrontend101
← Problems
#11EasyJavaScript functions

11. Debounce

JavaScriptClosures & ScopeAsync & Promises

Implement debounce(fn, wait) that delays invoking fn until after `wait` milliseconds have elapsed since the last call.

Example 1:
const debounced = debounce(save, 200);
debounced();
debounced(); // resets timer; runs once 200ms after last call
solution.js
Invokes function only once after wait period
(async () => {
          let count = 0;
          const fn = debounce(() => { count++; }, 30);
          fn();
          fn();
          fn();
          expect(count).toBe(0);
          await new Promise((r) => setTimeout(r, 60));
          expect(count).toBe(1);
        })()