Skip to content

Instantly share code, notes, and snippets.

@jimkang
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimkang/9165436 to your computer and use it in GitHub Desktop.
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.
var spacedOutSearchProducts = space(searchProducts, 1000);
spacedOutSearchProducts('one');
spacedOutSearchProducts('two');
spacedOutSearchProducts('three');
spacedOutSearchProducts('four');
// Now searchProducts will be called four times, one second apart.
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