2017-09-09 1 views
0

Dies ist der Code:setTimeout nicht innerhalb der Karte ausgeführt? oder setTimeOut auf Kartenfunktion?

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

alle Werke, sondern setzen eine Auszeit funktioniert nicht, sie alle zugleich auf js Bewertung spielen. Wie mache ich die Map-Ausführung mit setTimeOut langsamer?

+3

'setTimeout (red.play(), 3000);' läuft sofort ... 'setTimeout (red.play, 3000) ; 'würde' red.play() 'ausführen, wenn das Zeitlimit abgelaufen ist ... P.S. Warum verwenden Sie '.map', wenn die Callback-Funktion nichts zurückgibt? Verwenden Sie stattdessen ".forEach" –

+0

Wenn 'red.play()' eine Funktion zurückgibt, sollten Sie @ JaromandaX advise folgen. – Redu

+0

wahr (unwahrscheinlich) –

Antwort

0

Neben dem Problem der direkten Aufruf der Funktionen in dem Timeout, schlage ich vor, ein Array für das Objekt verwenden wihout eine switch ... case Syntax: Wenn alles funktioniert gut

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

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

weiß nicht Warum, wie reagieren behandelt mp3s, habe ich versucht, und gibt Fehler zurück, dass .play() ist keine Funktion –

+0

was 'typeof' ist' play'? –

0

und Sie wollen Gebrauch Zeit Zeitintervall als 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 Zählung als Zeitintervall für die anderen auch

Verwandte Themen