Created
June 30, 2018 17:54
-
-
Save jsphkhan/f950b3f0b2238083357234b345e65476 to your computer and use it in GitHub Desktop.
JavaScript Event Debouncing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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