Skip to content

Instantly share code, notes, and snippets.

@lightscalar
Created April 1, 2020 21:16
Show Gist options
  • Save lightscalar/8878a974b4d5ebe866239e44952a5e03 to your computer and use it in GitHub Desktop.
Save lightscalar/8878a974b4d5ebe866239e44952a5e03 to your computer and use it in GitHub Desktop.
Debounce for API calls based on key up.
function debounce(callback, wait) {
  let timeout;
  return (...args) => {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => callback.apply(context, args), wait);
  };
}

window.addEventListener('keyup', debounce( () => {
    // code you would like to run 1000ms after the keyup event has stopped firing
    // further keyup events reset the timer, as expected
}, 1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment