1

Sorry if this has already been answered, I am just learning Javascript and can't seem to figure this one out.

I have the anonymous function below, which reads a json file and updates the html. It successfully updates every 30 s, the problem is I have to wait 30 s for the data to appear when the page loads. How can I modify the code below so it updates on load, and then it updates every 30 s?

$(function () {
  setTimeout(function() {
  $.ajaxSetup({ cache: false });  
  $.getJSON("data/ticket_data.json", function(result){
  /*some more stuff here*/
  });
},30000);
});
  • 2
    Make it a named function. Call the named function yourself, then pass the named function to `setInterval()`. – jfriend00 Jun 28 '15 at 21:16
  • 1
    You may also be interested in `setIntervalAndExecute(...)` shown here: http://stackoverflow.com/questions/7424155/javascript-how-to-get-setinterval-to-start-now/7424165#7424165 if this comes up more than just once. – jfriend00 Jun 28 '15 at 21:18

1 Answers1

5

Give the function a name, call it, and put the setTimeout in $.getJSON's callback:

$(document).ready(getTicketData);

function getTicketData() {
    $.ajaxSetup({ cache: false });
    $.getJSON("data/ticket_data.json", function (result) {
        /*some more stuff here*/
        setTimeout(getTicketData, 30000);
    });
}

If you ever need to stop this timeout, have a look at clearTimeout().

blex
  • 24,941
  • 5
  • 39
  • 72