简体   繁体   English

setTimeout 不在地图内执行? 或 setTimeOut 地图功能?

[英]setTimeout not executing inside of map? or setTimeOut on map function?

this is the code:这是代码:

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++;
}

all works but set time out is not functioning, they all play at the same time upon js evaluation.所有工作但设置超时不起作用,它们都在js评估时同时播放。 how do I make map execution slower with setTimeOut?如何使用 setTimeOut 使地图执行速度变慢?

You can use this trick:你可以使用这个技巧:

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

It will delay each sub function in map 1 second它会将地图中的每个子功能延迟 1 秒

If all works well and you want time interval use time as 3000,6000,9000如果一切正常并且您希望时间间隔使用时间为3000,6000,9000

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

set count as time interval for others as well也将计数设置为其他人的时间间隔

Beside the problem of direct calling of the functions in the timeout, I suggest to use an array for the object wihout using a switch ... case syntax:除了在超时中直接调用函数的问题之外,我建议使用switch ... case语法为对象使用数组:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM