FrontendInterviews.dev

Loading problem…

24. Throttle Function

Easy•

Implement a basic throttle function that limits how often a function can be called.

In this version, the throttled function should execute immediately on the first call, then ignore all subsequent calls made within the next delay milliseconds.

Unlike debounce, throttle does not wait for calls to stop. It allows one call, then blocks repeated calls until the delay window has passed.

Requirements

1. Basic Functionality

  • Accept a function fn and a delay delay in milliseconds
  • Return a new throttled function
  • Execute fn immediately on the first call
  • After execution, ignore any calls made within the next delay milliseconds
  • Once the delay window has passed, allow the next call to execute

2. Behavior for This Problem

  • This is the basic throttle version
  • Calls made during the blocked window should be ignored
  • Do not schedule a trailing call
  • Do not replay the latest ignored arguments later

3. Context and Arguments

  • Preserve the this context of the call site
  • Pass all arguments correctly to fn

4. Edge Cases

  • Treat null, undefined, NaN, or negative delay values as 0
  • If delay is 0, calls are only blocked for the current synchronous execution timing and future calls may run again immediately on later ticks

Example Usage

const fn = (x) => console.log(x);
const throttled = throttle(fn, 100);

throttled(1); // runs immediately
throttled(2); // ignored
throttled(3); // ignored

setTimeout(() => {
  throttled(4); // runs after 100ms window has passed
}, 120);

Constraints

  • The throttled function should preserve the `this` context.
  • All arguments should be passed correctly to the original function.
  • Calls made during the delay window should be ignored.
  • Do not schedule trailing execution in this basic version.
  • Handle edge cases: null, undefined, NaN, negative delay, and zero delay.
Accepted36/53|Acceptance Rate67.9%