Skip to content

Instantly share code, notes, and snippets.

@camille-hdl
Created May 16, 2014 14:06
Show Gist options
  • Save camille-hdl/9585ebfd5290078df3e2 to your computer and use it in GitHub Desktop.
Save camille-hdl/9585ebfd5290078df3e2 to your computer and use it in GitHub Desktop.
Function throttle implementation in JS, with default parameters, using closures.
/* throttle(func,ms,context) returns a function that can't be called more than once every ms milliseconds.
context and ms parameters are optionnal.
*/
var throttle = (function(window){
var defaultMs=50;
return function (func,ms,context){
var to;
var wait=false;
return function(){
var args = Array.prototype.slice.call(arguments);
var later = function(){
func.apply(context || window,args);
};
if(!wait) {
later();
wait = true;
to = setTimeout(function() {
wait = false;
},ms || defaultMs);
}
};
};
})(window);
/*
Usage :
function myMoveHandler(e) {
// magic here
}
var throttledHandler = throttle(myMoveHandler);
window.addEventListener('mousemove',throttledHandler);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment