Last active
March 14, 2016 06:39
-
-
Save not-an-aardvark/70fab35125a723354cd8 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
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