Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery array/call function from array in order

Tags:

arrays

jquery

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.

like image 597
mtwallet Avatar asked Apr 09 '26 13:04

mtwallet


2 Answers

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.

like image 114
Tatu Ulmanen Avatar answered Apr 12 '26 12:04

Tatu Ulmanen


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');
    }
});
like image 28
nemisj Avatar answered Apr 12 '26 13:04

nemisj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!