Skip to content

debounce

Mike Byrne edited this page Jan 25, 2022 · 3 revisions

description

Returns a function that will only run N milliseconds after it stops being called. Or optionally will only run once during multiple calls, and won't run again until N milliseconds after the last call.

requires

  • nothing

parameters

  • func - required - function to be debounced
  • wait - required - delay after last call fire the func
  • immediate - optional - triggers the func immediately but then won't trigger it again until the wait time has passed after the last call

returns

  • debounced function

example usage:

var resized = debounce(function() {
  // function to run, 250ms after the resize has ended
}, 250);

window.addEventListener('resize', resized);
var clicked = debounce(function() {
  // function to run on first click, but won't run again until clicking has stopped for 1000ms
}, 1000, true);

document.addEventListener('click', clicked);

thanks to:

https://davidwalsh.name/javascript-debounce-function