![](/img/trans.png)
[英]How to check if a callback function passed as a parameter in Javascript has arguments or not?
[英]Javascript: parameter takes a random value when not passed in a callback function
我定期進行ajax投票。 為了達到相同的目的,我有以下代碼行:
window.setInterval(pollForBids, 5000);
函數pollForBids定義如下:
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);
}
});
}
我在代碼中還有其他地方需要參數,但在這種情況下,我不需要。 但是,警報每5秒給我一個隨機整數值。 難道不是總是不確定的嗎?
正如Mozilla開發人員中心所指出的那樣:“ setInterval()將在回調函數被調用后延遲毫秒數”。
通常當然,你傳遞給回調函數setInterval
沒有參數,所以你要在你這個“遲到的毫秒”值supplierId
參數。
還請注意,無論回調是否完成,都會每5秒調用一次setInterval
。
你為什么不使用像
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);
}
});
}
嘗試在setInterval中將函數包裝在匿名函數中:
window.setInterval( function() {
pollForBids();
}, 5000);
這將防止將隨機數傳遞到pollForBids函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.