使用jQuery在基于ajax的轮询中setTimeout的问题 [英] Issue with setTimeout in ajax based polling using jquery

查看:336
本文介绍了使用jQuery在基于ajax的轮询中setTimeout的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我需要每5秒钟使用ajax轮询一个URL.该URL返回一个json响应.下面是我在$ {document).ready中编写的代码.但是,setTimeout()函数不起作用.收到响应后立即调用startPoll()函数.我想在收到响应后暂停5秒钟,然后再次调用startPoll函数.有什么办法解决这个问题?

In my code i need to poll a url after every 5 seconds using ajax . The URL returns a json response. Below is the code that i wrote inside $(document).ready to do this. But,the setTimeout() function does not work. The startPoll() function is called immediately after the response is received.I want to halt for 5 seconds after response is received before calling the startPoll function again . Any way to fix this ?

$(document).ready(function(){


   var startPoll = function() {
         $.post('<url>', {},onPollRequestComplete, 'json');

   }

   var onPollRequestComplete = function(response) {

        responseObject = eval(response);

        if(responseObject.success) {
            //Do something here
        }

        setTimeout(startPoll(),5000); /*Make next polling request after 5 seconds*/         

}

startPoll();

});

谢谢

推荐答案

这是您的问题:

setTimeout(startPoll(),5000);

您将立即呼叫startPoll,而不是5秒钟后.相反,您应该像这样传递函数引用:

You're calling startPoll immediately, not after 5 seconds. Instead, you should pass in the function reference, like so:

setTimeout(startPoll,5000);

如果您希望每5秒触发一次轮询,即使以前的轮询不起作用(遇到服务器错误),也应该使用setInterval.如果您希望能够在出现错误的情况下停止轮询,那么现在拥有的代码非常有用.

If you want the polling to fire every 5 seconds even if previous polls didn't work (a server error was encountered), you should use setInterval instead. The code you have now is great if you want to be able to stop polling in case of errors.

这篇关于使用jQuery在基于ajax的轮询中setTimeout的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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