I’m searching for a solution where I’m able to run different functions, but some of them need a timeout and all following functions need to wait until the previous one is finished. Every function should be able to break the complete process.
Now I thought pushing all functions to a stack and loop through them:
function foo() {
// bar() should wait as long the following is finished:
setTimeout(function(){
if ((new Date()).getSeconds() % 2) {
alert('foo');
// break loop through functions (bar is not called)
}
else {
// start next function (bar is called)
}
}, 1000);
}
function bar() {
setTimeout(function(){
alert('bar')
}, 1000);
}
var functions = new Array('foo', 'bar');
for (var i = 0, length = functions.length; i < length; i++) {
window[functions[i]]();
}
But how to include wait/break?!
Note: This should work with 2+ functions (amount of functions is changeable)
Note2: I don’t want to use jQuery.
Note: I have updated my answer, see bottom of post.
Alright, let’s take a look.
You’re using the
window[func]()method, so you should be able to store and use return values from each function.Proof:
Let’s create a return rule:
If function returns
true, continue execution flow.If function returns
false, break execution flow.Now let’s put it into practice.
Depending on when you execute the script, eg, an even or uneven time period, it will only execute function
aor execute functionsab&c. In between each function, you can go about your normal business.Of course, the conditions probably vary from each individual function in your case.
Here’s a JSFiddle example where you can see it in action.
With some small modification, you can for instance, make it so that if function
areturns false, it will skip the following function and continue on to the next, or the one after that.Changing
To this
Will make it skip one function, every time a function returns false.
You can try it out here.
On a side-note, if you were looking for a waiting function that “pauses” the script, you could use this piece of code.
Update
After adjusting the code, it now works with
setTimeout.The idea is that you have an entry point, starting with the first function in the array, and pass along an index parameter of where you currently are in the array and then increment index with one to execute the next function.
Example | Code