Skip to content

Instantly share code, notes, and snippets.

@to
Created January 25, 2012 15:15
Show Gist options
  • Save to/1676724 to your computer and use it in GitHub Desktop.
Save to/1676724 to your computer and use it in GitHub Desktop.
throttleAndDebounce
Function.prototype.throttleAndDebounce = function(threshold, delay){
threshold = threshold || 100;
delay = delay || threshold;
var me = this;
var expire = 0;
var timeout;
return function(){
if(timeout)
clearTimeout(timeout);
var now = Date.now();
if(expire < now){
timeout = null;
expire = now + threshold;
me.apply(this, arguments);
} else {
var args = arguments;
timeout = setTimeout(function(){
timeout = null;
me.apply(self, args);
}, delay);
}
};
}
var start = Date.now();
var echo = (function(){
console.log(Date.now() - start);
}).throttleAndDebounce(1000, 2000);
setTimeout(echo, 0);
setTimeout(echo, 600);
setTimeout(echo, 1200);
setTimeout(echo, 1800);
setTimeout(echo, 2400);
setTimeout(echo, 2800);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment