Last active
December 17, 2015 16:09
-
-
Save bloodyowl/5636857 to your computer and use it in GitHub Desktop.
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 throttle(fn, duration){ | |
var lastCall = new Date().getTime() // closure variable | |
, timeout = null | |
duration = parseInt(duration, 10) // convert duration to int | |
function throttled(){ | |
var currentCall = new Date().getTime() | |
, gap = currentCall - lastCall | |
, self = this, args = arguments | |
if(timeout) { | |
window.clearTimeout(timeout) | |
timeout = null | |
} | |
if(gap < duration) { | |
timeout = window.setTimeout(function(){ | |
throttled.call(self, arguments) | |
}, Math.max(throttle - gap, 0)) | |
// if gap < 0, timeout is equivalent to setImmediate | |
return | |
} | |
// otherwise call | |
fn.call(self, args) | |
// and set the last callTime to now (takes care of not using `currentCall`, | |
// as fn.call can take time | |
lastCall = new Date().getTime() | |
} | |
return throttled | |
} |
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
/* Test */ | |
var calls = [] | |
, throttleCalls = 0 | |
, normalCalls = 0 | |
, scroller = throttle(function(){ | |
throttleCalls++ | |
calls.push(new Date().getTime()) | |
}, 100) | |
window.addEventListener("scroll", scroller) | |
window.addEventListener("scroll", function(){ | |
normalCalls++ | |
}) | |
function getStats(){ | |
var r = [], l = calls.length | |
for(;l--;) r[l] = calls[l] - (calls[l-1] || calls[l]) | |
return { | |
throttleIntervals : r, | |
normalCalls : normalCalls, | |
throttleCalls : throttleCalls | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Throttle
Test output :