Skip to content

Instantly share code, notes, and snippets.

@sethmcleod
Last active March 19, 2016 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethmcleod/b16bac0440ae1143afb5 to your computer and use it in GitHub Desktop.
Save sethmcleod/b16bac0440ae1143afb5 to your computer and use it in GitHub Desktop.
This limits the rate at which a function can fire, for optimized performance.
function debounce(func, wait, immediate) {
let timeout;
return function() {
const context = this, args = arguments;
const later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment