Q:

Timer in Ajax - Preemption

So this thing was going in my mind for a long time whether the timer that is given in an AJAx after which it has to send another request, what if it is smaller than the actual time taken by the requested file to complete its operation.
for example, consider the below code,
<div class="item"></div>
<script>
function timeLeft() {
  $(".item").each(function() {
    $this = $(this);
    var dataString = {s: "//some data", st: "<?echo $stamp?>"};
    $.ajaxSetup({cache:false});
    $.ajax({
      type: "POST",
      url: "get_content_home.php",
      dataType: "html",
      data: dataString, 
      success: function(result) {
        $this.html(result);
      }
    });
  });
}
window.setInterval(function() {
  timeLeft();
}, 100);
</script>

the timer given here is 100ms and the file get_content_home.php will be requested every 100m. What if get_content_home.php takes 500ms to complete its operations. Will the get_content_home.php be preempted and will be requested again? or will the timer wait and delay itself.
Thanks in advance.

A:

It's worse than you thought since the ajax request is in a loop.
What's gonna happen is actually :

window.setInterval call timeLeft
timeLeft call the AJAX request to get_content_home.phpone time for each .item element.
Let's say one AJAX call take 500ms, you'll do this five time before the first AJAX request return something (hence 5xnumber of .item calls before one result).

To stop this craziness, put your AJAX call outside of the loop and put the window.setInterval in the AJAX callback function:
$.ajax({
  type: "POST",
  url: "get_content_home.php",
  dataType: "html",
  data: dataString, 
  success: function(result) {
    $this.html(result);
    window.setTimeOut(function() {
      timeLeft();
    }, 100);
  }
});

and call timeLeft(); just once at the start.

