比方说,我有一个“ Foo”类的div集合,我想一遍又一遍地逐步更改文本的颜色。每个forEach
应该一次运行此更改,但是我需要再次运行该函数才能再次更改它们。
如果我想重复以继续运行此功能,我最好的选择是什么?我应该把它放在while循环中吗?
function colorWords() {
let textBoxes = document.querySelectorAll(".foo");
let colors = ["yellow","blue","green","red"];
textBoxes.forEach((word, index) => {
setTimeout(() => {
word.style.color = colors[Math.floor(Math.rand()*colors.length)]
}, 500 + index*250);
},
}
答案 0 :(得分:1)
您可能需要setInterval。
也用Math.random()替换Math.rand()
let colors = ["yellow", "blue", "green", "red"];
let interval
setInterval(() => {
let textBoxes = document.querySelectorAll(".foo");
textBoxes.forEach((word, index) => {
interval = index;
word.style.color = colors[Math.floor(Math.random() * colors.length)]
}, 500 + interval * 250)
})
<div class='foo'>1</div>
<div class='foo'>1</div>
<div class='foo'>1</div>
<div class='foo'>1</div>
<div class='foo'>1</div>
答案 1 :(得分:1)
您可以使用setInterval来控制循环段时间。下面,我将间隔设置为250ms,以了解更新的频率:
let INTERVAL_IDS = []
document.querySelector('#start').addEventListener('click',start)
document.querySelector('#stop').addEventListener('click',stop)
function start(){
let colors = ["yellow", "blue", "green", "red"];
let textBoxes = document.querySelectorAll(".foo");
INTERVAL_IDS.push(setInterval(function(){
textBoxes.forEach(word =>
word.style.color = colors[Math.floor(Math.random() * colors.length)]
)
},250))
}
function stop(){
clearInterval(INTERVAL_IDS.pop())
}
<button id="start">start</button><button id="stop">stop</button>
<span class='foo'>H</span>
<span class='foo'>e</span>
<span class='foo'>l</span>
<span class='foo'>l</span>
<span class='foo'>o</span>
答案 2 :(得分:-3)
是的,带计数器的while循环听起来很合理。 setInterval函数内部的所有内容在这么多秒后触发。
let counter = 0
while( counter >= 10){
*your code*;
counter++
}```