Facebook Pixel

Throttle

JavaScript
medium
25 mins

Implement a throttle function that takes a callback function and a delay time (in milliseconds) as arguments. The throttled function should ensure that the callback is executed at most once in the specified time period, regardless of how many times it's called.

Unlike debounce (which resets the timer with each call), throttle guarantees function execution at regular intervals while calls are being made.

Example

const throttledFn = throttle(() => console.log('Function called!'), 1000); // If called multiple times in quick succession throttledFn(); // Executes immediately throttledFn(); // Ignored throttledFn(); // Ignored // ... after 1000ms throttledFn(); // Executes throttledFn(); // Ignored

Constraints

  • The function should execute immediately on the first call
  • Subsequent calls within the delay period should be ignored
  • After the delay period, the next call should execute immediately
  • The throttled function should return the result of the callback function

Companies:

google
twitter
linkedin
airbnb

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.