Last active
August 29, 2015 13:56
-
-
Save jimkang/9165436 to your computer and use it in GitHub Desktop.
Wraps a function such that the execution of calls to that function are spaced out by the wait time specified. It's like throttling, except that instead of ignoring calls that happen too close together, it queues them for later.
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
var spacedOutSearchProducts = space(searchProducts, 1000); | |
spacedOutSearchProducts('one'); | |
spacedOutSearchProducts('two'); | |
spacedOutSearchProducts('three'); | |
spacedOutSearchProducts('four'); | |
// Now searchProducts will be called four times, one second apart. |
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
function space(func, wait) { | |
var queuedFunctionsAndContexts = []; | |
var timeoutChainRunning = false; | |
function queueFn() { | |
// Capture 'this' and args for when the function runs later. | |
queuedFunctionsAndContexts.unshift({ | |
fn: func, | |
context: this, | |
args: arguments | |
}); | |
if (!timeoutChainRunning) { | |
timeoutChainRunning = true; | |
runNextFn(); | |
} | |
function runNextFn() { | |
// Get the next function to go. | |
var next = queuedFunctionsAndContexts.pop(); | |
// Run it if it exists. | |
if (next && next.fn) { | |
next.fn.apply(next.context, next.args); | |
// Schedule the next run. | |
setTimeout(runNextFn, wait); | |
} | |
else { | |
timeoutChainRunning = false; | |
} | |
} | |
} | |
return queueFn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment