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
This is your problem:
You’re calling
startPollimmediately, not after 5 seconds. Instead, you should pass in the function reference, like so: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
setIntervalinstead. The code you have now is great if you want to be able to stop polling in case of errors.