Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout not executing inside of map? or setTimeOut on map function?

Tags:

javascript

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. how do I make map execution slower with setTimeOut?

like image 854
gpbaculio Avatar asked May 11 '26 04:05

gpbaculio


2 Answers

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

like image 82
Dung Nguyen Avatar answered May 13 '26 18:05

Dung Nguyen


If all works well and you want time interval use time as 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

like image 40
Niklesh Raut Avatar answered May 13 '26 17:05

Niklesh Raut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!