Throttle - Problem

Given a function fn and a time in milliseconds t, return a throttled version of that function.

A throttled function is first called without delay and then, for a time interval of t milliseconds, can't be executed but should store the latest function arguments provided to call fn with them after the end of the delay.

For instance, t = 50ms, and the function was called at 30ms, 40ms, and 60ms:

• At 30ms: function executes immediately without delay
• At 40ms: function is blocked, arguments stored
• At 60ms: arguments overwrite the stored ones from 40ms
• At 80ms (30ms + 50ms): function executes with the latest arguments from 60ms

The throttled function should create another delay period after each execution.

Input & Output

Example 1 — Basic Throttling
$ Input: fn = (x) => console.log(x), t = 100
Output: throttled function
💡 Note: Creates a throttled version that executes immediately on first call, then blocks for 100ms while storing latest arguments
Example 2 — Multiple Calls During Cooldown
$ Input: fn = (a,b) => console.log(a+b), t = 50
Output: throttled function
💡 Note: Function executes first call immediately, subsequent calls during 50ms cooldown period store latest arguments for delayed execution
Example 3 — Long Cooldown Period
$ Input: fn = () => console.log('fired'), t = 1000
Output: throttled function
💡 Note: With 1000ms cooldown, function executes immediately then ignores calls for 1 second, executing with latest args after cooldown

Constraints

  • 0 ≤ t ≤ 1000
  • 1 ≤ calls.length ≤ 10
  • 0 ≤ calls[i].t ≤ 1000
  • 0 ≤ calls[i].inputs.length ≤ 10

Visualization

Tap to expand
Function Throttling ConceptOriginalFunctionfn(args)Throttle WrapperExecute ImmediateStore & DelayThrottledFunctionRate LimitedThrottling Timelinet=0ms: Execute ✓t=30ms: Blockt=50ms: Store argst=100ms: Execute stored ✓Result: Controlled execution rate with latest arguments preserved
Understanding the Visualization
1
Input Function
Original function with timing parameter t
2
Throttle Logic
Add timing control and argument storage
3
Controlled Output
Function executes at controlled intervals
Key Takeaway
🎯 Key Insight: Execute immediately on first call, then batch subsequent calls during cooldown period
Asked in
Facebook 35 Google 28 Amazon 22
23.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen