Skip to content

Instantly share code, notes, and snippets.

@philbirnie
Created June 5, 2016 15:25
Show Gist options
  • Select an option

  • Save philbirnie/893950093611d5c1dff4246a572cfbeb to your computer and use it in GitHub Desktop.

Select an option

Save philbirnie/893950093611d5c1dff4246a572cfbeb to your computer and use it in GitHub Desktop.
Debounce function; based heavily on underscore's but updated for ES6
// 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.
const debounce = function(func, wait, immediate) {
let timeout;
return function(...args) {
const later = function() {
timeout = null;
if (!immediate) Reflect.apply(func, this, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) Reflect.apply(func, this, args);
};
};
module.exports = debounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment