jQuery GetJSON在SetTimeOut计时器内 [英] JQuery GetJSON inside SetTimeOut Timer

查看:87
本文介绍了jQuery GetJSON在SetTimeOut计时器内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以发布示例代码,其中包含一个运行中的计时器(javascript settimeout)并进行数据检索.

Can anyone post a sample code wherein theres a running timer(javascript settimeout) and doing data retrieval..

这个计时器的基本作用是显示新消息.

basically what i this timer does is to display new messages..

myFunction(param){

//data retrieval operation
//using getJSON.. call displaydata() base on param

settimeout("myFunction()", param, 1000);

}

function displaydata(param){

//processing
alert('test')}

我应该使用getJSON吗?我认为异步调用存在问题.

Should i use getJSON? i think theres a problem with the asynchronous call..

推荐答案

我注意到有两点需要在代码中修复.

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

  • setTimeout()方法的参数不正确
  • 您的异步getJSON调用将在下一次超时和getJSON方法的结果之间创建竞争条件.改为执行此操作:
  • 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);

这篇关于jQuery GetJSON在SetTimeOut计时器内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆