首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >遍历Javascript中的函数

遍历Javascript中的函数
EN

Stack Overflow用户
提问于 2018-08-28 07:05:11
回答 2查看 76关注 0票数 0

我正在尝试遍历javascript中的六个函数。当用户将鼠标悬停在较小的图像上时,每一个都会更改图像的图像源。我知道如何遍历数组,但我似乎不能遍历函数。还有一种方法可以让它在循环到下一个函数之前等待几秒钟。感谢你能提供的任何帮助。

EN

回答 2

Stack Overflow用户

发布于 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()并重复该链。

票数 3
EN

Stack Overflow用户

发布于 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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52048018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档