Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Last active February 20, 2017 13:28
Show Gist options
  • Save YozhEzhi/f42f1ffd090d7343e2f4fa65adf48cea to your computer and use it in GitHub Desktop.
Save YozhEzhi/f42f1ffd090d7343e2f4fa65adf48cea to your computer and use it in GitHub Desktop.
JS debounce
function debounce(fn, delay) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(context, args), delay);
}
}
// Usage:
function foo() {
// code here;
}
// fires once per 500 milliseconds.
const elem = document.getElementById('elem');
elem.addEventListener('scroll', debounce(foo, 500));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment