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.
2 Answers
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.
3 Comments
CodeMonkey
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?
CodeMonkey
Thanks that did the trick. It was exactly what i was looking for.
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
CodeMonkey
That worked but how do you make it so that it keeps looping though the array instead of only going through it once?
dhilt
@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.