JQuery GetJSON inside SetTimeOut Timer

北城以北 提交于 2019-12-01 14:05:28

Two things I noticed you need to fix in your code.

  • The setTimeout() method has some incorrect arguments
  • Your asynchronous getJSON call creates a race condition between the next timeout and the result of the getJSON method. Do this instead:

.

function yourFunction(params) {  
    jQuery.getJSON("url", {data}, function(data, textStatus){
        // handle your JSON results

        // Call the timeout at the end of the AJAX response
        // This prevents your race condition
        setTimeout(function(){
            yourFunction(params);
        }, 1000);
    }
} 

setTimeout(function(){
    yourFunction(params);
}, 1000);

The first parameter should be a function literal or a function reference and the second parameter should be the milliseconds.

setTimeout( function() {
    getData('param')
}, 1000);

function getData() {
     $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
        function(data){
          $.each(data.items, function(i,item){
            $("<img/>").attr("src", item.media.m).appendTo("body");
            if ( i == 3 ) return false;
          });
        });
}

I'm not using the actual argument in my example but you can easily update it to do so. Also I wasn't sure if you were polling ( this doesn't do poll/recursive calling ).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!