Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Last active December 17, 2015 16:09
Show Gist options
  • Save bloodyowl/5636857 to your computer and use it in GitHub Desktop.
Save bloodyowl/5636857 to your computer and use it in GitHub Desktop.
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
}
/* 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
}
}
@bloodyowl
Copy link
Author

Throttle

Test output :

{
     "throttleIntervals":[
        0,
        128,
        100,
        101,
        102,
        103,
        109,
        121,
        114,
        101,
        100,
        100,
        1411,
        105,
        105,
        114,
        109,
        100,
        21363,
        126,
        118,
        104,
        107,
        101,
        100,
        103,
        101,
        100,
        100,
        119,
        111,
        116,
        118,
        120,
        120,
        129,
        101,
        117,
        100,
        101,
        100,
        109,
        125,
        118,
        116,
        100,
        131,
        101,
        100,
        105,
        102,
        128,
        122,
        121,
        121,
        102,
        122,
        114,
        139,
        113,
        101,
        100,
        109
     ],
     "normalCalls":153,
     "throttleCalls":63
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment