以下是代码:
while(countLoop < count) {
let randIndex = Math.floor(Math.random()*4); // returns // 1 to 3 decimal, this will be used for colors indexes
console.log("while true count = ",randIndex)
this.setState(
({colorsChallengeForUser}, props) => ({
colorsChallengeForUser: [...colorsChallengeForUser, randIndex]
}),
() => { // setState has a default callback we make use of that here.
let { colorsChallengeForUser } = this.state;
colorsChallengeForUser.map((item, index, array) => {
switch(item) {
case 0:
// red.play()
setTimeout(red.play(), 3000);
break;
case 1:
// green.play()
setTimeout(green.play(), 3000);
break;
case 2:
// yellow.play()
setTimeout(yellow.play(), 3000);
break;
case 3:
// yellow.play() // this wo
setTimeout(blue.play(), 3000);
break;
defalt:
console.error(`Unknown ${item}`);
}
});
}
);
countLoop++;
}
所有的工作都正常,但设置超时不起作用,它们在js评估时同时播放。我该如何使用setTimeOut使映射执行变慢?
setTimeout(red.play(), 3000);
会立即运行...setTimeout(red.play, 3000);
将在定时器到期时执行red.play()
... P.S. 当回调函数不返回任何内容时,为什么要使用.map
?请改用.forEach
。 - Jaromanda Xred.play()
返回一个函数,否则您应该遵循 @JaromandaX 的建议。 - Redu()
,但它仍然“不工作”...浏览器开发者工具控制台中有任何错误吗? - Jaromanda X