I am a beginner in javascript and jquery and was looking for an efficient way to long poll in jquery. I came across this piece of code and was puzzled by the attribute complete: . I am aware of the use of 'complete' but will this piece of code result in recursive function call?
(function poll(){
$.ajax({ url: "server", success: function(data){
//Update your dashboard gauge
salesGauge.setValue(data.value);
}, dataType: "json", complete: poll, timeout: 30000 });
})();
Thanks in advance. :)
You can avoid the recursion by using a short timeout to ensure that the current call stack clears:
(function poll(){
$.ajax({
url: "server",
success: function(data){
//Update your dashboard gauge
salesGauge.setValue(data.value);
},
dataType: "json",
complete: function () {
setTimeout(poll, 0);
},
timeout: 30000
});
})();
This will execute poll
as (probably) the next event after the current execution clears. In other words, jQuery will execute the complete
callback and return from everything until it's finally out of its onreadystatechange
callback, at which point the JavaScript runtime will execute poll
again (unless a different event came in and got onto the event queue first, of course).