views:

174

answers:

2

Hello,

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();

});

Thank You

+1  A: 

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"&gt;&lt;/script&gt;
    <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>
Phil
Thanks for the reply Phil.setInterval didnt work either :(
johnswr
I think it was your code, I've put an edited version in which works for me now.
Phil
+2  A: 

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.

Magnar
Thanks Magnar, that fixed it ! :)
johnswr