2017-09-09 58 views
0

這是代碼:setTimeout在地圖內部不執行?或setTimeOut在地圖功能?

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

'的setTimeout;'立即運行...'的setTimeout(red.play,3000) ;'在超時到期時執行'red.play()'...你爲什麼在回調函數沒有返回任何東西時使用'.map'?使用'.forEach'代替 –

+0

除非'red.play()'返回一個函數,否則你應該遵循@JaromandaX提示。 – Redu

+0

是真的(不太可能) –

回答

0

除了在超時功能直接調用的問題,我建議使用一個數組對象wihout使用switch ... case語法:

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

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

不知道爲什麼如何處理MP3,我試過,並返回錯誤.play()不是一個函數 –

+0

'typeof'是'play'? –

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; 
    ....... 

集數爲他人以及()red.play(3000)的時間間隔