FrontendPro

27Implement throttle() with leading and trailing options

mediumAbout 35 minutesCodingtimersclosuresperformance

Problem

Implement throttle(fn, wait, { leading = true, trailing = true } = {}). The throttled function calls fn at most once per wait milliseconds, however often it is called.

  • leading: true calls fn immediately on the first call of a quiet period.
  • trailing: true makes sure the last call made during a waiting period is not lost: fn runs with its arguments when the period ends.

Also add cancel(), which drops any pending trailing call.

const onScroll = throttle(() => updateProgressBar(), 100);
window.addEventListener("scroll", onScroll);

Requirements

  • Call fn with the arguments and this of the call that triggered it.
  • A trailing call starts a new waiting period, so two calls are never closer than wait apart.
  • With leading: false, the first call only schedules a trailing call.
  • If nothing was called during a waiting period, no trailing call happens.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthroughs

Stuck? Watch someone solve it, then try again on your own.

Throttling in Javascript | Walmart Frontend Interview QuestionAkshay Saini on YouTubeOpen on YouTube
Javascript Interview Questions ( Debouncing and Throttling ) - Implementation, Examples etcRoadsideCoder on YouTubeOpen on YouTube

Step-by-step

A timer represents the current waiting period. While it runs, fn must not be called directly. When it is null, the throttle is idle.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever