Javascript: parameter takes a random value when not passed in a callback function
I am doing an ajax poll periodically. To achieve the same I have the following 开发者_开发知识库line of code:
window.setInterval(pollForBids, 5000);
The function pollForBids is defined as follows:
function pollForBids(supplierId){
alert(supplierId);
$.ajax({
method: "GET",
url : "/enterprize-sourcing/refreshBids.do",
async : true,
cache : false,
data : {action : "refreshList",
eventId : eventId,
lastRetrieveTime: makeFinite(latestBidTime, 0),
supplierId : makeFinite(supplierId, "")},
success: function(xml){
refreshBids(xml);
}
});
}
I have other places in the code where I need the parameter, but in this particular case I do not. But, the alert gives me a random integer value every 5 seconds. Shouldn't it always be undefined?
As the Mozilla Developer Center states: "setInterval() will pass the number of milliseconds late the callback was called into the callback function".
MDC
Usually of course the callback function you pass to setInterval
takes no parameters, so you're getting this "milliseconds late" value in your supplierId
parameter.
Also be warned that setInterval
will be called every 5 seconds whether your callback has completed or not.
Try wrapping your function in an anonymous function in the setInterval:
window.setInterval( function() {
pollForBids();
}, 5000);
This will prevent the random number from being passed into the pollForBids function.
why dont you use something like
function pollForBids(supplierId){
if (typeof supplierId == "undefined") {
supplierId = "default value";
}
$.ajax({
method: "GET",
url : "/enterprize-sourcing/refreshBids.do",
async : true,
cache : false,
data : {action : "refreshList",
eventId : eventId,
lastRetrieveTime: makeFinite(latestBidTime, 0),
supplierId : makeFinite(supplierId, "")},
success: function(xml){
refreshBids(xml);
}
});
}
精彩评论