Frontend101 logoFrontend101
← Problems
#12MediumJavaScript functions

12. Throttle

JavaScriptClosures & ScopeAsync & Promises

Implement throttle(fn, wait) so fn executes at most once every `wait` milliseconds.

Example 1:
const throttled = throttle(onScroll, 100);
solution.js
Ignores calls during cooldown window
(async () => {
          let count = 0;
          const fn = throttle(() => { count++; }, 40);
          fn();
          fn();
          fn();
          expect(count).toBe(1);
          await new Promise((r) => setTimeout(r, 60));
          fn();
          expect(count).toBe(2);
        })()