问题
In the code below, I had the expectation that this would create a polling loop that would fire off every 10 seconds to get a "job status report" from the server. It seems it is creating over 100 calls per second.
I got my education from this excellent article, but I seem to be misreading it.
function UpdateEstimates() {
var request = { jobID: ExportVM.get("ticketID") };
var jqxhr = $.ajax({
type: "GET",
url: AppGlobals.serverURL + "GetJobStatus",
data: request,
contentType: "application/json; charset=utf-8",
complete: UpdateEstimates,
timeout: 10000,
dataType: "json"
});
jqxhr.done(function (data) { NewEstimates(data); });
jqxhr.fail(function (data) { alert('new estimates request failed'); });
}
The call is very low overhead, so I can handle easily 1 second updates, but I really don't like the continuous 100/sec rate very much. Is there some way to introduce a delay into the call loop?
回答1:
timeout in $.ajax is not doing what you actually think. It just sets the timeout for that particular call (maximum allowed time). You will have to wrap this in setTimeout function.
回答2:
I would suggest to re-trigger the timeout on the 'complete' hook. In this fashion you prevent overlapping reqs.
Tear the 'timeout' param off - as @tomca32 explained timeout is about a req that would take too long.
It would be something like:
function UpdateEstimates() {
var request = { jobID: ExportVM.get("ticketID") };
var jqxhr = $.ajax({
type: "GET",
url: AppGlobals.serverURL + "GetJobStatus",
data: request,
complete: scheduleUpdEstimates,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
jqxhr.done(function (data) { NewEstimates(data); });
jqxhr.fail(function (data) { alert('new estimates request failed'); });
function scheduleUpdEstimates(){
setTimeout(function(){ UpdateEstimates(); }, 10000);
}
来源:https://stackoverflow.com/questions/16364928/polling-every-10-seonds