Javascript 用 setTimeout 递归循环数组?

标签 javascript arrays recursion

我在 ES6 中有这样的代码:

function loopLettersEvery3Seconds() {
    const letters = ['a', 'b', 'c'];

    let offset = 0;
    letters.forEach((letter, index) => {
      setTimeout(() => {
        // I do something with the letter, nothing important
      }, 3000 + offset);
      offset += 3000;
      if (index === letters.length - 1) {
        loopLettersEvery3Seconds(letters);
      }
    });
}

这个函数循环遍历一个字母数组,每 3 秒我就可以对每个字母执行一些操作。但问题是,当这个循环结束并完成时,我无法再次重复该过程...递归调用会产生堆栈溢出(未捕获的范围错误:超出最大调用堆栈大小)哈哈

告诉我怎么做!谢谢!!

BR

最佳答案

你可以做这样的事情。这是通过递归和 setTimeouts 模拟 setInterval 的方法

var array = ['a', 'b', 'c']

function loopLettersEvery3Seconds(arr, index) {
    if (index === arr.length) return;
    //Do stuff with array
    setTimeout(loopLettersEvery3Seconds, 3000, arr, index+1)
}
loopLettersEvery3Seconds(array, 0)

这样,您就不必处理循环的同步性质,而是根据调用堆栈和 Web API 执行所有操作(这是超时的正确术语吗?)

如果你想让它永远循环,那就这样做

var array = ['a', 'b', 'c']

function loopLettersEvery3Seconds(arr, index) {
    if (index === arr.length) return loopLettersEvery3Seconds(arr, 0);

    setTimeout(loopLettersEvery3Seconds, 3000, arr, index+1)
}
loopLettersEvery3Seconds(array, 0)

关于Javascript 用 setTimeout 递归循环数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564396/

相关文章:

javascript - 检测 ajax 成功函数何时需要超过 5 秒并重定向

javascript - 在创建的表行中使用 Bootstrap Datepicker

javascript - 引用数组中的对象时遇到问题

求解 nPr(排列)的算法。对于傻瓜

python - 使用Python递归进行日常编码挑战

recursion - 计算递归的复杂度

javascript - 将回调传递给深度嵌套函数的最佳实践

javascript - 即使发现错误,Ajax 仍在执行

c++使用数组作为参数时出现free错误

ruby - 数组中的字母顺序,顶部有多个默认值