我正在尝试遍历javascript中的六个函数。当用户将鼠标悬停在较小的图像上时,每一个都会更改图像的图像源。我知道如何遍历数组,但我似乎不能遍历函数。还有一种方法可以让它在循环到下一个函数之前等待几秒钟。感谢你能提供的任何帮助。
发布于 2018-08-28 07:19:22
我不确定我是否完全理解你的问题。也许这段代码会有帮助?
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);
}
每个函数在调用下一个函数之前都会执行一些代码(在1000ms延迟之后)。myFunction3()
将调用myFunction1()
并重复该链。
发布于 2018-08-28 07:25:30
首先,它可能是一个函数数组:
// 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]();
}
如果你想在延迟的情况下串联运行它们,你可以使用最简单的递归计时器方法:
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);
https://stackoverflow.com/questions/52048018
复制相似问题