Docs

JS Machine Coding Questions — Implementations You Must Know

Throttle


  • Run the function at most once per wait ms — classic for scroll and mousemove.
  • Key insight: Track last execution time; either skip calls inside the window (leading) or schedule one trailing call (trailing).
  • Debounce vs throttle: debounce waits for silence; throttle caps frequency.
  • For requestAnimationFrame-style scroll, consider a rAF throttle instead of time-based.
1function throttle(fn, wait, options = {}) { 2 const { leading = true, trailing = true } = options; 3 let lastTime = 0; 4 let timeoutId; 5 6 return function (...args) { 7 const now = Date.now(); 8 const remaining = wait - (now - lastTime); 9 10 if (remaining <= 0 || remaining > wait) { 11 if (timeoutId) { clearTimeout(timeoutId); timeoutId = undefined; } 12 lastTime = now; 13 if (leading) fn.apply(this, args); 14 } else if (trailing && !timeoutId) { 15 timeoutId = setTimeout(() => { 16 lastTime = Date.now(); 17 timeoutId = undefined; 18 fn.apply(this, args); 19 }, remaining); 20 } 21 }; 22}