简体   繁体   中英

javascript polling at given time interval

Following function is being called at every 10 second.

function getData()
    {      
        $.ajax({
              url       : "refresh.php",
              type      : "POST",
              data      : {"id" : id},            
              success   : function(data) {
                 $(".show").html(data);
              }
          });
    }
        $(document).ready(function(){
      setInterval("getData()",50000);//Polls in every 50 sec
    });

What I want is: when page is loaded, getData() should be called instantly, after that each call should be at given interval ie 50second

how to do this?

Just add a manual call to getData() in the dom ready handler

function getData() {
    $.ajax({
        url: "refresh.php",
        type: "POST",
        data: {
            "id": id
        },
        success: function (data) {
            $(".show").html(data);
        }
    });
}
$(document).ready(function () {
    setInterval("getData()", 50000); //Polls in every 50 sec
    getData(); //invoke on page load
});

Call the function from the ready event.

Also, use the function reference in the setInterval call rather than a string.

$(document).ready(function(){
  setInterval(getData,50000);
  getData();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM