开发者

Issue with setTimeout in ajax based polling using jquery [duplicate]

开发者 https://www.devze.com 2022-12-13 04:25 出处:网络
This question already has answers here: Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
This question already has answers here: Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate] (3 answers) Closed 8 years ago.

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 so开发者_开发知识库mething here
        }

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

}

startPoll();

});

Thank You


This is your problem:

setTimeout(startPoll(),5000);

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

setTimeout(startPoll,5000);

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.


I think rather than setTimeout you need to use setInterval

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var startPoll = function() {
                $.post('url', {}, function(response) {
                    var responseObject = eval(response);

                    if (responseObject.success) {
                        alert('hi');
                    }
                }, 'json');
            }

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

        });
    </script>
</head>
<body>
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号