← JavaScript Coding

Throttle with Leading and Trailing

hardtimersclosuresperformance
Asked at
Flipkart
Google
LinkedIn
Meta
Swiggy
Flipkart, Google, LinkedIn, Meta, Swiggy

Problem statement

Implement throttle(func, wait, options). Throttling ensures a function runs at most once per wait window.

Options

  • leading: whether to run on the first call in a window. Defaults to true.
  • trailing: whether to run once more with the latest arguments after the window ends. Defaults to true.

Requirements

  • Preserve this and latest arguments.
  • Support leading-only, trailing-only, both, and neither.
  • Add cancel() to clear pending trailing calls.
  • Return the latest invocation result from the wrapper.

Requirements & constraints

  • →Do not use lodash or external libraries.
  • →Support both leading and trailing options.
  • →Expose a cancel method.

How to approach Throttle with Leading and Trailing

The strategy an interviewer expects you to reach for.

Throttle with leading/trailing options is the “scroll handler” API: fire immediately, then at most once per window, optionally catching the last call. Naive move Ignore calls inside the window entirely. Users lose the final scroll position update. Where it breaks Leading-off should not fire at the start. Trailing-off should not schedule the tail. Rapid calls must refresh the trailing timer with the latest args. The fix Track lastCallTime, lastArgs, and a timer. If enough time passed and leading is on, invoke now. Else if trailing is on, schedule one timeout for the remaining wait with the newest args. Remember: Trailing exists to keep the last event; leading exists for instant feedback. Say this in the interview: I'd track last invoke time, optionally fire immediately on the leading edge, and schedule a single trailing call with the latest args when calls keep arriving inside the window.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

JS CodingMedium

86. API Retry

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Flipkart interview
  • Google interview
  • LinkedIn interview
  • Meta interview
  • Swiggy interview