2017-02-23 3 views
-1

目標はコンテナの境界内のランダムな場所にdivを作成し、3秒待ってからdivを破棄します。すすぎ、3回繰り返します。しかし、私が知ることから得られる結果は、setTimeoutが3秒間待機している間、コードは「ループ」を続け、3秒後にsetTimeout内の関数が実行されます。私は誤って2つのスレッドを作成しましたか?なぜコードは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

で最初のバグを削除することができますイベントループ、javascriptのsetTimeout関数が本質的に非ブロッキングであり、非同期と呼ばれるという事実です。あなたは、タイマー内のタイマーをネストしているhttps://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop

+0

私はそれについての感情を持っていました。見ていただき、ありがとうございます。 – brooklynsweb

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フィドルを見てください。 – FelisPhasma

+0

FelisPhasma:あなたのメモごとに '.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>

関連する問題