Last active
August 18, 2016 01:47
-
-
Save russellbeattie/b6b71b1e5b48122866fb6f77fdbd5567 to your computer and use it in GitHub Desktop.
A better, self-contained, JavaScript function throttle
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, limit, scope) { | |
var last; | |
var deferTimer; | |
return function() { | |
var context = scope || this; | |
var args = arguments; | |
var now = Date.now(); | |
var diff = now - last; | |
clearTimeout(deferTimer); | |
if (diff < limit) { | |
deferTimer = setTimeout(function() { | |
last = Date.now(); | |
fn.apply(context, args); | |
}, limit - diff); | |
} else { | |
last = now; | |
fn.apply(context, args); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment