Created
October 28, 2015 07:06
-
-
Save jaawerth/1fdd3dee73ef8747def9 to your computer and use it in GitHub Desktop.
A basic throttle implementation
This file contains 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
/* Simple implementation of "throttle". | |
* Option object has boolean properties 'trailing' and 'leading', where 'leading' | |
* defaults to true. | |
**/ | |
function throttle(fn, period, opts) { | |
opts = opts || {}; | |
var leading = opts.leading === false ? false : true; // defaults to true | |
var trailing = !!opts.trailing; // defaults to false | |
var args, cached; | |
var timeout = null, prev = 0; | |
return function() { | |
var now = Date.now(); | |
if (!leading && !prev) prev = now; | |
var timeLeft = period - (now - prev); | |
args = []; | |
for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); // faster slice | |
if (timeLeft <= 0 || timeLeft > period) { | |
clear(); | |
prev = now; | |
cached = fn.apply(this, args); | |
if (!timeout) args = null; | |
} else if (!timeout && trailing) { | |
timeout = setTimeout(deferred.bind(this), timeLeft); | |
} | |
return cached; | |
}; | |
function clear() { | |
if (timeout) clearTimeout(timeout); | |
timeout = null; | |
} | |
function deferred() { | |
prev = leading ? Date.now() : 0; | |
timeout = null; | |
cached = fn.apply(this, args); | |
if (!timeout) args = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment