How to run "setInterval" without initial delay?

Asked

Viewed 296 times

4

In this code below, it updates a div every 20 seconds. Only when entering the page I have to wait 20 seconds for it to appear. I would like it to appear already at the beginning, when entering the page.

<div id="latestData"><img src="img/loading3.gif" /></div>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function () {
       setInterval(function() {
          $.get("includes/principal/contador_mapa.php", function (result) {    
              //nome da pagina com o select mysql
              $('#latestData').html(result);  // nome da DIV
          });
       }, 20000); // segundos
    });
</script>
  • I don’t know if it’s a good idea to use setInterval in that case. http://answall.com/questions/77764/por-que-dizem-recursividade-settimeout-%C3%A9-better-than-setinterval/77765#77765

2 answers

1


You can create a function with the code of that request and call it before you put it on setInterval.

$(function () {
    function getContadorMapa() {
        $.get("includes/principal/contador_mapa.php", function (result) {
            $('#latestData').html(result);
        });
    }

    getContadorMapa(); // primeira chamada
    setInterval(getContadorMapa, 20000);
});

1

You can do a function to the part that returns itself, and when it is executed the first time it leaves itself as argument in setInterval.

$(function () {
    var $latestData = $('#latestData'); // para ficar em cache e não precisar de fazer mais que 1 vez
    function contadorMapa() {
        $.get("includes/principal/contador_mapa.php", function (result) {
            $latestData.html(result);
        });
        return contadorMapa; // <-- assim quando fôr executada a primeira vez deixa no seu lugar a função
    }
    setInterval(getContadorMapa(), 20000);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.