Debouncing in Javascript

Last modified: 
Tuesday, June 20th, 2017

Example of debouncing taken from underscore.js and this David Walsh blog post: https://davidwalsh.name/javascript-debounce-function .

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
let debounce = (func, wait, immediate) => {
  let timeout;
  return function() {
    let context = this, args = arguments;
    let later = function() {
      timeout = null;
      (!immediate) && func.apply(context, args);
    };
    let callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    (callNow) && func.apply(context, args);
  };
};

// logClick() can only triggered once every 500 
// milliseconds. Setting `immediate` to `true` 
// ensures the event fires at the beginning of the
// cycle.
let logClick1 = debounce(() => {
  console.log('logClick1');
}, 500, true);

document.addEventListener("click", logClick1);

// Omitting the `immediate` flag causes the event
// to trigger at the end of the wait cycle.
let logClick2 = debounce(() => {
  console.log('logClick2');
}, 500);

document.addEventListener("click", logClick2);

JS Bin on jsbin.com


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.