FrontendInterviews.dev

Loading problem…

25. Enhanced Throttle Function

Medium•
Acceptance: 66.67%
•
🔓3/3 Pro unlocks today

This problem builds on throttle-function. Complete that first, then load your solution to continue.

Implement an enhanced throttle function that extends the basic throttle functionality with advanced features like cancellation, flushing, and return value handling.

Requirements

1. Basic Functionality

  • Accept a function fn and a delay delay in milliseconds
  • Return a throttled function with additional methods: cancel() and flush()
  • Execute fn at most once per delay milliseconds
  • If called multiple times within the delay period, only execute once

2. Advanced Features

Cancel Method

  • The throttled function should have a cancel() method
  • Calling cancel() should cancel any pending execution
  • Should be safe to call multiple times

Flush Method

  • The throttled function should have a flush() method
  • Calling flush() should immediately execute any pending call
  • Should return the result of the function execution
  • Should not schedule a new execution after flushing

Return Value Handling

  • The throttled function should return the result of fn when executed
  • If execution is pending, return the last result (or undefined if none)
  • When flushed, return the actual result

3. Context Preservation

  • Preserve the this context of the original function call
  • Pass all arguments correctly to the throttled function

Example Usage

// Example: Throttling with cancel
const handleScroll = (event) => {
  console.log('Scroll position:', event.scrollY);
  return event.scrollY;
};

const throttledScroll = throttle(handleScroll, 100);

window.addEventListener('scroll', throttledScroll);
throttledScroll.cancel(); // Cancels any pending execution

// Example: Flushing pending calls
const throttledFn = throttle((x) => x * 2, 100);
throttledFn(5); // Schedules execution
const result = throttledFn.flush(); // Executes immediately, returns 10

Constraints

  • The throttled function must have cancel() and flush() methods
  • cancel() should safely cancel any pending execution
  • flush() should execute pending call immediately and return the result
  • The throttled function should preserve the 'this' context
  • All arguments should be passed correctly to the original function
  • Return value should be handled correctly
  • Handle edge cases: null/undefined delay, zero delay, null function