简体   繁体   English

加载时执行匿名函数,然后使用setTimeout每30秒再次执行一次

[英]Execute anonymous function on load, then execute again every 30 seconds using setTimeout

Sorry if this has already been answered, I am just learning Javascript and can't seem to figure this one out. 抱歉,如果已经回答了这个问题,我正在学习Javascript,似乎无法弄清楚这一点。

I have the anonymous function below, which reads a json file and updates the html. 我下面有匿名函数,该函数读取json文件并更新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. 它每30秒成功更新一次,问题是我必须等待30秒才能在页面加载时显示数据。 How can I modify the code below so it updates on load, and then it updates every 30 s? 如何修改下面的代码,使其在加载时更新,然后每30秒更新一次?

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

Give the function a name, call it, and put the setTimeout in $.getJSON 's callback: 给函数命名,调用它,并将setTimeout放入$.getJSON的回调中:

$(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() . 如果您需要停止此超时,请查看clearTimeout()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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