2017-02-23 65 views
-1

目標是在容器邊界內的隨機位置創建一個div,等待3秒鐘然後銷燬div;沖洗並重復3次。然而,根據我所知,結果是,雖然setTimeout等待三秒,但代碼繼續'循環',並且僅在3秒內setTimeout內部的函數才執行。我無意中創建了兩個線程嗎?爲什麼代碼跳過setTimeout,只有稍後才趕上?

$(document).ready(function() { 
     var $bug = "<div class='bug'><div>"; 
     var x = 0; 

     var timer = setInterval(function() { 
      if (x > 3) { 
       clearInterval(timer); 
      } 
      r1 = Math.floor((Math.random() * 270) + 1); 
      r2 = Math.floor((Math.random() * 270) + 1); 
      $('#container').append("<div class='bug'style='top:" + r1 + "px;left:" + r2 + "px;'></div>") 
      x++; 

      setTimeout(function() { 
       $('.bug').remove(); 
      }, 3000) 

     }, 1000); 
    }); 

回答

0
$('.bug').remove(); 

這將刪除所有.bug在頁面上。您可以通過給它與索引另一個類解決這個問題:

$('#container').append("<div class='bug bug" + x + "'style='top:" + r1 + "px;left:" + r2 + "px;'></div>") 

然後你就可以通過

$('.bug.bug0').remove(); 

JS FIDDLE

+1

我考慮過這個問題,但我們的目標是消除幾秒鐘後產生的錯誤,所以永遠不會有真正的錯誤數組哈,雙關。 – brooklynsweb

+0

@brooklynsweb沒有任何錯誤。看看js小提琴,只是一個bug的索引。 – FelisPhasma

+0

FelisPhasma:根據您的註釋'.bug'將從scree中刪除所有類的所有錯誤。我回應的是,我的目標是在創建它幾秒鐘後刪除創建的bug,因此屏幕上不會有多個錯誤。這樣做'.bug'基本上刪除了只包含1個錯誤的一組錯誤。不過,我原來的問題與其他問題有關。 – brooklynsweb

0

您的定時器嵌套在一個計時器,計時器,因爲是異步的,你無法預測何時會發生什麼。在你的情況下,定時器的嵌套特性導致失控效果。

實際上,根本沒有必要擁有setTimeout

的說明,請參見注釋:

$(function() { 
 
    
 
    function insertRandom(){ 
 
    var r1 = Math.floor((Math.random() * 270) + 1); 
 
    var r2 = Math.floor((Math.random() * 270) + 1); 
 
    $('#container').append("<div class='bug' style='position: relative; top:" + 
 
          r1 + "px; left:" + r2 + "px;'>Test</div>") 
 
    } 
 
    
 
    // Insert the random element immediately 
 
    insertRandom(); 
 
    
 
    var x = 0; // counter for repetition 
 
    
 
    // Start code at a regular interval 
 
    var timer = setInterval(function() { 
 
    
 
     // If we're over the count 
 
     if (x >= 3) { 
 
     // Stop the code 
 
     clearInterval(timer); 
 
     
 
     // Terminate the function 
 
     return; 
 
     } 
 
     
 
     // Increment the count 
 
     x++; 
 

 
     // Take out the last inserted elmeent 
 
     $('.bug').remove(); 
 
     
 
     // Put a new element in 
 
     insertRandom(); 
 

 
    }, 3000); 
 
    
 

 
});
#container { border:1px solid black; width:300px; height:300px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="container"></div>

相關問題