setInterval(function() { $.get('test.php', function(data) { $('.test').append(data); }); }, 2000); 

File test.php:

 echo time(); 

In <div class="test"></div> can get from 2 to 4 identical values. What could be the problem?

    2 answers 2

    @ROOT , why complicate things like that, there is a proven solution:

     setTimeout(function loop() { $.get('test.php', function(data) { $('.test').append(data); // условие опционально setTimeout(loop, 2000); }); }, 2000); 

      1) add clearInterval so that they do not accumulate (inside)
      2) issue the get package to an additional function and, using an additional blocking variable, prohibit calling this function until you receive a successful response from test.php

      • @ROOT, clearInterval will stop setInterval. And how can I run it again? - ModaL
      • @Spectre, please issue a response. Mark as true :) - ModaL
      • 1) clearInterval - you need not to create a new interval each time, using setTimeout 2) In the case of the @Spectre code, without a blocking variable, you do not have the opportunity to handle an error when the data arrives later than 2 seconds - Maksym Prus