我在 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/