Reputation: 5968
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?
Upvotes: 9
Views: 14091
Reputation: 309
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
Upvotes: 19
Reputation: 386654
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:
var options = [red, green, yellow, blue];
// call with
setTimeout(options[item].play, 3000);
// ^^^^ index
// ^^ without calling the function
Upvotes: 0
Reputation: 34914
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
Upvotes: 1