Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active Feb 11, 2018
Embed
What would you like to do?
//Debounce returns a function, based on input:
//1. trigger function for debouncing - func
//2. time to debounce (waiting time - only call after this amount of secs passed - wait
//3. immediate - true/false whether trigger function immediately or wait until the debouncing time.
//Logic:
//1. Save arguments, save context
//2. Clear timeout - start again the counter
//3. if (immediate and no timeout - aka first run - run it.
//4. set Time out for triggering func with wait time, in which if not immediate (false), then clear timeout and trigger func.
function debounce(func, wait, immediate = false){
var timeout;
return function(){
var context = this, args = arguments;
var later = function(){
timeout = null;
if(!immediate){
func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow){
func.apply(context, args);
}
}
}
}
function handleScroll(){
}
var handleScrollListener = debounce(handleScroll, 200);
window.addEventListener('scroll', handleScrollListener);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment