2017-02-23 66 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>

相关问题