Skip to content Skip to sidebar Skip to footer

Why Does The Code Skip The Settimeout And Only Later Catch Up?

The goal is to create a div in a random location within the bounds of the container, wait 3 seconds then destroy the div; rinse and repeat 3 times. The outcome however, from what I

Solution 1:

I believe it has got something to do with event loops and the fact that javascript setTimeout function is non-blocking in nature and is called asynchronous.

Refer : https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop

Solution 2:

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

This will remove every .bug in on the page. You can fix this by giving it another class with an index:

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

And then you can remove the first bug by

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

JS FIDDLE

Solution 3:

You are nesting a timer within a timer and because timers are asynchronous you can't predict what will happen when. In your case, the nested nature of the timers causes a runaway effect.

Actually, there is no need to have setTimeout at all.

See comments for explanation:

 $(function() {
 
   functioninsertRandom(){
     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 immediatelyinsertRandom();
   
   var x = 0;  // counter for repetition// Start code at a regular intervalvar timer = setInterval(function() {
   
      // If we're over the countif (x >= 3) { 
        // Stop the codeclearInterval(timer); 
        
        // Terminate the functionreturn;
      }
      
      // Increment the count
      x++;

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

  }, 3000);
  

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

Post a Comment for "Why Does The Code Skip The Settimeout And Only Later Catch Up?"