Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active February 11, 2018 12:08
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 mayashavin/42b5298797ba67127d0578c159fccc48 to your computer and use it in GitHub Desktop.
Save mayashavin/42b5298797ba67127d0578c159fccc48 to your computer and use it in GitHub Desktop.
//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