Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Created June 30, 2018 17:54
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 jsphkhan/f950b3f0b2238083357234b345e65476 to your computer and use it in GitHub Desktop.
Save jsphkhan/f950b3f0b2238083357234b345e65476 to your computer and use it in GitHub Desktop.
JavaScript Event Debouncing
var ref = document.querySelector('#myDiv');
function foo() {
console.log('hello');
}
function debounce(callback, time) {
var timer = null;
return function() {
clearTimeout(timer);
timer = setTimeout(function() {
callback.call(null);
}, time);
}
}
//onscroll fires every time you scroll which is bad for performance
//debounce function delays the execution of the foo function.
//when you scroll continously, the callback foo function is called
//every 1s
ref.addEventListener('scroll', debounce(foo, 1000), false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment