如何在for循环中使用setInterval遍历多个JavaScript数组?
解决方案:间隔遍历多数组并延迟输出
原代码的问题在于普通for循环是同步执行的,所有迭代会瞬间完成,不会有延迟;如果之前用setInterval没成功,大概率是没处理好索引递增和停止条件。下面给你两个可行的实现方案:
方法一:使用 Async/Await + setTimeout
这个方法逻辑直观,利用异步函数特性让每次迭代等待1秒后再执行下一次,容易维护。
const noteW = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteE = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteR = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteI = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteO = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteP = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] // 封装延迟函数 const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); async function iterateArrays() { const arrLength = noteW.length; for (let i = 0; i < arrLength; i++) { // 检查当前索引下各数组的值 if (noteW[i] === 1) console.log('shieeet1'); if (noteE[i] === 1) console.log('shieeet2'); if (noteR[i] === 1) console.log('shieeet3'); if (noteI[i] === 1) console.log('shieeet4'); if (noteO[i] === 1) console.log('shieeet5'); if (noteP[i] === 1) console.log('shieeet6'); // 等待1秒再进入下一次迭代 await delay(1000); } // 所有迭代完成后输出 console.log('Iteration complete'); } // 启动遍历 iterateArrays();
方法二:使用 setInterval
如果坚持用setInterval,需要手动维护索引变量,在合适时机清除定时器:
const noteW = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteE = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteR = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteI = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteO = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] const noteP = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1] let currentIndex = 0; const arrLength = noteW.length; const intervalId = setInterval(() => { // 索引超出范围时停止定时器并输出完成信息 if (currentIndex >= arrLength) { clearInterval(intervalId); console.log('Iteration complete'); return; } // 检查当前索引下各数组的值 if (noteW[currentIndex] === 1) console.log('shieeet1'); if (noteE[currentIndex] === 1) console.log('shieeet2'); if (noteR[currentIndex] === 1) console.log('shieeet3'); if (noteI[currentIndex] === 1) console.log('shieeet4'); if (noteO[currentIndex] === 1) console.log('shieeet5'); if (noteP[currentIndex] === 1) console.log('shieeet6'); // 索引递增 currentIndex++; }, 1000);
内容的提问来源于stack exchange,提问作者8bitNostalgia
相关产品推荐
相关产品推荐

