Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

debounce: run after calls pause

`debounce` combines a burst of calls into one. In the version shown here, only the last call runs, after the calls have paused.

Version: User-defined debounce helper using web timers; host timer behavior varies

Syntax

const debounced = debounce(fn, waitMs);
debounced(...args);
debounced.cancel();

debounce(fn, waitMs) returns a wrapper around fn. Pass the function fn, not the result of calling it, and a non-negative delay waitMs in milliseconds. Create the wrapper once for a given source of calls and reuse it, for example to filter results after someone pauses typing.

With trailing-edge debounce, each call cancels the pending timer and starts a new one. When the timer finally fires, fn runs once with the arguments and this from the last wrapper call. If calls keep arriving quickly enough, fn may never run. Throttling instead limits how often work runs even while calls continue. A leading-edge variant runs fn immediately on the first call of a burst; the example does not do this.

Each wrapper has its own timer. The example's cancel() method drops a pending invocation but does not stop work that has already started. The wrapper returns undefined immediately, not the later result of fn. An exception thrown by fn in the timer callback does not propagate back to the earlier caller of the wrapper.

The example defines debounce and its cancel() method; neither is defined by ECMAScript or a web standard. The version information refers to the standards the example relies on, not to the helper itself. The example uses the host's setTimeout and clearTimeout. Choose a waitMs within the range supported by the host's timers: a value above that range may be treated as a much shorter delay. The timer can fire later than requested. Outside a browser, check whether and how the runtime provides timers.

Examples

(() => {
  function debounce(fn, waitMs) {
    let timer;

    function cancel() {
      if (timer !== undefined) {
        clearTimeout(timer);
        timer = undefined;
      }
    }

    function debounced(...args) {
      cancel();
      timer = setTimeout(() => {
        timer = undefined;
        Reflect.apply(fn, this, args);
      }, waitMs);
    }

    debounced.cancel = cancel;
    return debounced;
  }

  const search = {
    prefix: 'Search: ',
    update: debounce(function (query) {
      console.log(this.prefix + query);
    }, 100),
  };

  search.update('c');
  search.update('ca');
  search.update('cat');
})();

Result

Search: cat

Run the entire snippet at once in a browser console. The three calls are synchronous, so only the last one leads to `Search: cat` being logged. The 100 ms delay does not guarantee an exact execution time.

Related lessons

  • JavaScript · Lesson 21 · Basic · Version: 4

Sources