在map函数内部使用setTimeout无法执行?或者在map函数中使用setTimeOut?

8

以下是代码:

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使映射执行变慢?


5
setTimeout(red.play(), 3000); 会立即运行... setTimeout(red.play, 3000); 将在定时器到期时执行 red.play()... P.S. 当回调函数不返回任何内容时,为什么要使用 .map?请改用 .forEach - Jaromanda X
除非 red.play() 返回一个函数,否则您应该遵循 @JaromandaX 的建议。 - Redu
true (unlikely) - Jaromanda X
@JaromandaX 谢谢,我会记住的。但是 setTimeout 仍然无法工作 :/ - gpbaculio
真的吗?你已经删除了 (),但它仍然“不工作”...浏览器开发者工具控制台中有任何错误吗? - Jaromanda X
我的错,我使用了map并尝试使用() => red.play(),但它没有起作用。但是使用foreach和回调函数,我没有返回它,所以它只在{}范围内。 - gpbaculio
3个回答

16

你可以使用这个技巧:

var arr = ["apple", "banana", "carrot"];
arr.map( (item, index) => {
  setTimeout(() => {
    // do stuff function with item
    console.log(item);
  }, 1000*index )
});

它将延迟map中每个子函数1秒钟


1
如果一切顺利,您想要时间间隔,请使用时间3000,6000,9000
var count = 0;
colorsChallengeForUser.map((item, index, array) => {
    count += 3000;
    switch(item) {
        case 0: 
            // red.play()
            setTimeout(red.play(), count);
        break;
    .......

将计数设置为时间间隔,适用于其他内容。


0
除了直接在超时中调用函数的问题外,我建议使用一个数组来处理对象,而不使用switch ... case语法:
var options = [red, green, yellow, blue];

// call with
setTimeout(options[item].play, 3000);
//                 ^^^^               index
//                           ^^       without calling the function

不知道为什么React如何处理MP3文件,我尝试了一下,但返回错误,提示“play()”不是一个函数。 - gpbaculio
playtypeof 是什么? - Nina Scholz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接