2012-11-27 107 views
5

我正在開發一個html5應用程序,我希望8秒後寫隨機的地方,它會寫如果你贏了或沒有一秒鐘,然後它會開始創建一個新的隨機,我已經試過用但它似乎沒有做任何事情,如果我寫(而真正的)瀏覽器崩潰。每9秒javascript循環?

有沒有辦法解決它?

jQuery(document).ready(function(){ 
    ImageClicked = false; 
    for (var i=0;i<8;i++){ 
     var XYScore = 0; 
     var RandomPlace=Math.floor((Math.random()*10)+1); 
     var Place; 
     var WantedXPr; 
     var WantedYPr; 

     switch(RandomPlace){ 
      case 1: 
       Place="Berlin"; 
       WantedYPr=790; 
       WantedXPr=4300; 
       break; 
      case 2: 
       Place="New York"; 
       WantedYPr=1061; 
       WantedXPr=2345; 
       break; 
      case 3: 
       Place="barcelona"; 
       WantedYPr=1049; 
       WantedXPr=4046; 
       break; 
      case 4: 
       Place="Johannesburg"; 
       WantedYPr=2546; 
       WantedXPr=4618; 
       break; 
      case 5: 
       Place="shanghai"; 
       WantedYPr=1272; 
       WantedXPr=6664; 
       break; 
      case 6: 
       Place="Moskau"; 
       WantedYPr=732; 
       WantedXPr=4800; 
       break; 
      case 7: 
       Place="kahir"; 
       WantedYPr=4690; 
       WantedXPr=1310; 
       break; 
      case 8: 
       Place="Delhi"; 
       WantedYPr=1323; 
       WantedXPr=5707; 
       break; 
      case 9: 
       Place="rio de genero"; 
       WantedYPr=2478; 
       WantedXPr=3050; 
       break; 
      case 10: 
       Place="Tokyo"; 
       WantedYPr=1180; 
       WantedXPr=7102; 
       break; 
     } 

     setTimeout(function(){ 
      if (ImageClicked==false){ 
       $('#HeaderAfterWrite').html(", all the people were killed"); 
       $('#HeaderWrite').html("No one helped ");} 
      else if(XYScore>69) 
       $('#HeaderWrite').html("Youv'e succesful recover the city "); 
      else if(XYScore>39) 
       $('#HeaderWrite').html("The Parvars are not all of "); 
      else {$('#HeaderAfterWrite').html("is full destroyed now!"); 
       $('#HeaderWrite').html(" ");} 
     }, 8000); 
     $('#Place').html(Place); 
    } 
}); 

回答

20

您可以通過

clearInterval(time); 
+4

除了命名區間鑑別'time',很好的答案。 ...以及w3schools是一個相當不好的參考。但是+1。 – CaffGeek

-1

使用的setInterval用於此目的

Reference

time=setInterval(function(){ 
//your code 
},9000); 

可以清除此是有辦法解決它。

發生超時的功能。

function setTimeoutAgain() 
{ 
    var t = setTimeout(function() 
    { 
     setTimeoutAgain(); 
    },8000); 
} 
+0

我該如何將它粘貼到我的代碼中(即時通訊只是一個JavaScript初學者)? –

3

這更優雅。

(function loop() { 
    setTimeout(function() { 
    // execute script 
    loop() 
    }, 9000); 
}());