Jquery array / call function from array in order

I am working on a project where I have a bunch of functions that I would like to call one by one in a certain order at the click of a button. Once one function has been executed, I do not want to use it again. I would like to move on to the next one.

It was suggested by another SO user that I need to use arrays, but I'm still learning jQuery and don’t know how to do this, can someone lead me in the right direction?

Thank you very much in advance.

+3
source share
3 answers

Code example:

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');
    }
});
+2
source

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; }

:

var functions = ['foo', 'bar'];

for(var i = 0; i <= functions.length; i++) {
    window[functions[i]]();
}

:

var functions = [foo, bar];

for(var i = 0; i <= functions.length; i++) {
    func();
}

, , , . , .

+3
var inarr = [func1,func2,func3];

for (afunc in inarr) {
   afunc();
}
0
source

Source: https://habr.com/ru/post/1731561/


All Articles