Skip to content

Instantly share code, notes, and snippets.

@not-an-aardvark
Last active March 14, 2016 06:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save not-an-aardvark/70fab35125a723354cd8 to your computer and use it in GitHub Desktop.
var _ = require('lodash');
function losslessThrottle(func, wait) {
var scheduledCalls = [];
return function() {
// Add a timestamp to `scheduledCalls` signifying when the current invocation will take place.
// The last element of `scheduledCalls` will be the timestamp of the latest scheduled invocation, so the current
// invocation should occur `wait` milliseconds after that.
var scheduledTimestamp = _.max([_.last(scheduledCalls) + wait, _.now()]);
scheduledCalls.push(scheduledTimestamp);
return _.delay(func.bind(this), scheduledTimestamp - _.now(), arguments);
};
}
_.mixin({losslessThrottle: losslessThrottle});
// ---
function myFunc() { console.log('called'); }
var throttled = _.losslessThrottle(myFunc, 1000);
throttled();
throttled();
throttled();
// (prints 'called' once at time=0, once at time=1, and once at time=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment