-
Notifications
You must be signed in to change notification settings - Fork 0
Sequencr.chain
Calls a chain of functions in order, separated by timeouts (defined by the timeout
argument). Sequencr.chain
is non-breaking, and the first callback in the callbacks
array won't be executed until after the first timeout. If an onCompleted
callback is required, set it as the last element of the callbacks
array. Replaces the all-too-common callback hell as this:
setTimeout(function(timeout)
{
function1();
setTimeout(function(timeout)
{
function2();
setTimeout(function(timeout)
{
function3();
}, timeout, timeout)
}, timeout, timeout)
}, 10, 10);
becomes this:
Sequencr.chain([function1, function2, function3], 10);
callbacks: An array of functions to be called one at a time. Functions may accept one parameter for the return value of the previous function.
timeout: Optional (default=1). The timeout in ms between each function call. This can be an integer, or a function that returns an integer.
Basic Usage
Sequencr.chain([function1, function2, function3], 10);
When you use the above code, the following things happen:
-
Sequencr.chain
is non-breaking, so the rest of your code will continue running as normal. - After 10ms,
function1
is called. - After another 10ms,
function2
is called. - After another 10ms,
function3
is called.
Piping Return Values
Functions that return a value will pass that value to the next function automatically. Each of your functions (except the first) may optionally accept the return value of the previous function as a parameter. Unfortunately, Sequencr.chain
per se does not return the final value because it's asynchronous. If this is something you need, check out Sequencr.promiseChain
.
Sequencr.chain([
function(){return 100},
function(x){return x * 2},
function(y){console.log(y)}
], 10);
//This will print 200 to the console.
Passing Parameters
To pass custom parameters (for instance, function2(a, b, c)
), use anonymous functions.
Sequencr.chain([function1, function()
{
function2(a, b, c);
}, function3], 10);
Preserving Scope
To preserve scope use JavaScript's built-in apply
function. Otherwise this
will refer to Sequencr
itself.
Sequencr.chain.apply(this, [[function1, function2, function3], 10]);