ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Simple Debounce Function

JavaScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function debounce(func, delay) {
2let timeoutId;
3return function(...args) {
4clearTimeout(timeoutId);
5timeoutId = setTimeout(() => {
6func.apply(this, args);
7}, delay);
8};
9}
Algorithm description viewbox

Simple Debounce Function

Algorithm description:

This algorithm implements a debounce function, a common pattern used to control the rate at which a function is executed. It ensures that a function is only called after a certain amount of time has passed without it being called again. This is widely used for tasks like handling user input in search bars or resizing events to prevent excessive computations.

Algorithm explanation:

The `debounce` function returns a new function that wraps the original `func`. When the debounced function is called, it clears any existing `setTimeout` timer and sets a new one. If the debounced function is called again before the `delay` has elapsed, the previous timer is cleared, effectively resetting the waiting period. Only when the timer completes without being reset will the original `func` be executed with the provided arguments and context. This prevents rapid, repeated calls from triggering the function multiple times in quick succession.

Pseudocode:

function debounce(func, delay):
  let timeoutId = null
  return function(...args):
    clear existing timeout using timeoutId
    set new timeout for delay milliseconds:
      execute func with original context and args
    store new timeoutId