Reputation: 876
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. :)
Upvotes: 1
Views: 439
Reputation: 11187
To answer the OP question:
"complete: poll" will call the function again over and over. This would result in quite a bit of bandwidth, possible server timeouts, and if used by enough people could slow your server down.
Upvotes: 1
Reputation: 46183
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).
Upvotes: 0