|
| 1 | +# Debounce Function |
| 2 | + |
| 3 | +## Challenge |
| 4 | +Implement a debounce function that delays the execution of a callback until after a specified delay period has elapsed since the last time it was invoked. |
| 5 | + |
| 6 | +## Problem Description |
| 7 | +Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often. It limits the rate at which a function can fire. |
| 8 | + |
| 9 | +### Real-World Use Cases |
| 10 | +- **Search Input**: Wait for the user to stop typing before making an API call |
| 11 | +- **Window Resize**: Wait for resize to finish before recalculating layout |
| 12 | +- **Scroll Events**: Reduce the number of scroll event handlers fired |
| 13 | +- **Button Clicks**: Prevent multiple form submissions |
| 14 | + |
| 15 | +## Example |
| 16 | + |
| 17 | +### Input |
| 18 | +```js |
| 19 | +function handleSearch(query) { |
| 20 | + console.log(`Searching for: ${query}`); |
| 21 | +} |
| 22 | + |
| 23 | +const debouncedSearch = debounce(handleSearch, 500); |
| 24 | + |
| 25 | +// User types rapidly |
| 26 | +debouncedSearch('J'); |
| 27 | +debouncedSearch('Ja'); |
| 28 | +debouncedSearch('Jav'); |
| 29 | +debouncedSearch('JavaScript'); |
| 30 | +``` |
| 31 | + |
| 32 | +### Output |
| 33 | +``` |
| 34 | +// Only executes once after 500ms of the last call |
| 35 | +Searching for: JavaScript |
| 36 | +``` |
| 37 | + |
| 38 | +## Requirements |
| 39 | +1. The debounce function should accept a function and a delay time |
| 40 | +2. It should return a new function that delays invoking the original function |
| 41 | +3. Each new call should reset the delay timer |
| 42 | +4. Only the last call should execute after the delay period |
| 43 | +5. The function should preserve the correct `this` context and arguments |
| 44 | + |
| 45 | +## Key Concepts |
| 46 | +- **Closures**: Maintaining state (timeoutId) across function calls |
| 47 | +- **Higher-Order Functions**: Returning a function from a function |
| 48 | +- **setTimeout/clearTimeout**: Managing asynchronous delays |
| 49 | +- **Function Context**: Using `apply()` to preserve `this` binding |
| 50 | + |
| 51 | +## Difference from Throttling |
| 52 | +- **Debounce**: Executes the function only after the calls have stopped for a specified period |
| 53 | +- **Throttle**: Executes the function at most once per specified time interval |
| 54 | + |
| 55 | +## Benefits |
| 56 | +- Improves performance by reducing unnecessary function calls |
| 57 | +- Reduces API calls and server load |
| 58 | +- Provides better user experience by preventing excessive updates |
0 commit comments