Skip to content

Instantly share code, notes, and snippets.

@camille-hdl
Last active August 29, 2015 14:01
Show Gist options
  • Save camille-hdl/f8c266cff6220d23d889 to your computer and use it in GitHub Desktop.
Save camille-hdl/f8c266cff6220d23d889 to your computer and use it in GitHub Desktop.
A debounce implementation in JS, with a default wait time. Useful when listening to window resize event for instance.
/* debounce(func,context,ms) returns a function that will be called only ms millisecond after it's latest call.
context and ms are optionnal.
*/
var debounce = (function(window){
var defaultMs=300;
return function (func,context,ms){
var to;
return function(){
var args = Array.prototype.slice.call(arguments);
if(!!to) clearTimeout(to);
to = setTimeout(function(){
func.apply(context || window,args);
},ms || defaultMs);
};
};
})(window);
/*
Usage :
function myResizeHandler() {
// magic here
}
var debouncedHandler = debounce(myResizeHandler);
window.addEventListener('resize',debouncedHandler);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment