0

I'm trying to loop through six functions in javascript. Each one changes the image source of an image when a user hovers over a smaller image. I know how to loop through arrays but I can't seem to loop through functions. Also is there a way to make it wait a few seconds before it loops to the next function. Thanks for any help you can offer.

1
  • 1
    I don't understand your question. By the way, can you post your code? Commented Aug 27, 2018 at 23:08

2 Answers 2

3

I'm not sure I fully understand your question. Perhaps this code will help?

function myFunction1() {
    // Some code you want to execute
    setTimeout(myFunction2, 1000);
}

function myFunction2() {
    // Some more code you want to execute
    setTimeout(myFunction3, 1000);
}

function myFunction3() {
    // Some final code you would like to execute before repeating the chain
    setTimeout(myFunction1, 1000);
}

Each function executes some code before calling the next function (after a 1000ms delay). myFunction3() will call myFunction1() and repeats the chain.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I tried something similar but basically what I'm trying to do is it after gets to the last function have it go back to the first one and run them all over again. Any idea how to do that?
;) the above code does exactly that. myFunction3() "runs them all again" by invoking myFunction1()
Thanks that did the trick. It was exactly what i was looking for.
0

First of all it may be an array of functions:

// the list of functions
const actionList = [];

// pushing functions to the list
actionList.push(func1);
actionList.push(func2);
...

// running functions in a loop
for(let i = 0; i < actionList.length; i++) {
  actionList[i]();
}

If you want to run them in series with some delay, you may use simplest recursive timer approach:

const run = function (actionList, index, delay) {
  setTimeout(function () {
    actionList[index](); // execute current index function immediately
    index++; // increment index...
    if(actionList[index]) { // ...while there are items in the list
      run(actionList, index, delay); // next index function will be executed after "delay" ms
    }
  }, delay);
}

run(actionList, 0, 1000);

2 Comments

That worked but how do you make it so that it keeps looping though the array instead of only going through it once?
@CodeMonkey The recursion did it for me. Please follow MDN Functions#Recursion guide, you'll see some examples with explanations. This is very basic concept and you really need it on your way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.