Last active
August 29, 2015 14:01
-
-
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.
This file contains hidden or 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
/* 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