setTimeout没有在map中执行?或地图函数的setTimeOut?

时间:2017-09-09 08:24:07

标签: javascript

这是代码:

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减慢地图执行速度?

3 个答案:

答案 0 :(得分:2)

您可以使用此技巧:

    arr.map( (item, index) => {
      setTimeout(() => {
        // do stuff function with item
      }, 1000*index )
    })
    

它将延迟地图中的每个子功能1秒钟

答案 1 :(得分:0)

除了在超时中直接调用函数的问题之外,我建议使用一个数组作为对象,而不是使用switch ... case语法:

var options = [red, green, yellow, blue];

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

答案 2 :(得分:0)

如果一切正常并且您希望时间间隔使用时间为3000,6000,9000

var count = 0;
colorsChallengeForUser.map((item, index, array) => {
    count += 3000;
    switch(item) {
        case 0: 
            // red.play()
            setTimeout(red.play(), count);
        break;
    .......

将计数设置为其他人的时间间隔