Skip to content

Instantly share code, notes, and snippets.

@gsusmonzon
Last active November 19, 2020 10:20
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 gsusmonzon/134825297dd72d15f8697398ab10b159 to your computer and use it in GitHub Desktop.
Save gsusmonzon/134825297dd72d15f8697398ab10b159 to your computer and use it in GitHub Desktop.
Vanilla Javascipt debounce utility
/**
* Debounce utility based on `underscore` debouce, but simpler
* usage: `_debounce(onScrollEvent, 100, true)`
* usually you want atBeginning set to false.
* use atBeginning if you want `func` is called when teh sequence of calls starts,
* instead of waiting until `wait` ms have passed without more calls
*/
window._debounce = window._debounce || function(func, wait, atBeginning) {
var timeout;
if (atBeginning){
return function() {
var context = this, args = arguments;
var callNow = !timeout;
timeout && clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
func.apply(context, args);
}, wait);
if (callNow) return func.apply(this, args);
}
} else {
return function() {
var context = this, args = arguments;
timeout && clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
func.apply(context, args);
}, wait);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment