I am working on a project where I have a bunch of functions that I would like to call one by one in a particular order when a button is clicked. Once one function has been performed I do not want to use again I would like to move onto the next one.
It has been suggested by another S.O user that I need to use arrays but I am still learning jQuery and unsure how to do this, can anyone get me started in the right direction?
Many thanks in advance.
Say you have functions like this:
function foo() { doSomeStuff; }
function bar() { doSomeOhterStuff; }
Or, an alternative but equal syntax:
var foo = function() { doSomeStuff; }
var bar = function() { doSomeOhterStuff; }
Then you can just create an array out of those function names and iterate them:
var functions = ['foo', 'bar'];
for(var i = 0; i <= functions.length; i++) {
window[functions[i]]();
}
Or you can pass the functions directly to the array:
var functions = [foo, bar];
for(var i = 0; i <= functions.length; i++) {
func();
}
The order you insert them to the array determines the order they are executed, and every function will be executed just once. Hope this helps.
Example code :
function fnc1(){/* some code in here */};
function fnc2(){/* some code in here */};
function fnc3(){/* some code in here */};
var fncs = [ fnc1, fnc2, fnc3 ];
$("buttonId").click(function(){
var currentFunction = (fncs.shift()); // removes first element from array
if(currentFunction){
currentFunction();
}else{
alert('No more functions available');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With