Created
January 25, 2012 15:15
-
-
Save to/1676724 to your computer and use it in GitHub Desktop.
throttleAndDebounce
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
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