FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Debounce

15mins

Debouncing is a technique used to improve performance by limiting how often a function can run. When you wrap a function with debounce, it delays its execution until a certain amount of time (the "wait" period) has passed since the last time it was called.

Think of typing into a search box: without debounce, the search function might run on every keystroke ("h", "he", "hel", "hell", "hello"), which is wasteful. With debounce, the function only runs once, after the user stops typing for the specified wait duration.

Your task is to implement a debounce(fn, wait) function that: -- Returns a debounced version of fn. -- Ensures fn only runs after wait milliseconds have passed since the last call. -- Supports two additional methods: 1)cancel(): Cancels any pending execution. 2)flush(): Immediately executes the pending function call, if any.

This problem tests your ability to work with closures, timers, and function state.

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests