我正在編寫谷歌瀏覽器擴展程序。我使用setTimeout來減慢對服務器的請求速度。但setTimeout不能按預期工作。它返回一個錯誤,說明沒有定義reqUrl。javascript setTimeout無法識別函數參數
基於對stackoverflow類似問題的答案,它似乎這是一個超出範圍的問題,我不明白如何解決它,除了使reqUrl一個全局變量,這似乎不是一個很好的解決方案。如果刪除括號,它就會失控,完全沒有時間延遲。
如何使這項工作?
這是代碼。儘管我認爲這不是問題的核心,但我已經列入了減速功能。
openDetailPg(profileLink[currentLink]);
function openDetailPg(reqUrl)
{
console.log('openDetailPg at '+reqUrl);
setTimeout("createDetailWindow(reqUrl)",slowDown());
++sendCount;
timeOfLastRequest=new Date().getTime();
};
function createDetailWindow(detailUrl)
{
console.log('createDetailWindow');
chrome.tabs.create({windowId: mainWindowId, url: detailUrl},
function (tab)
{
console.log(' OpenDetailPg Created Tab '+tab.id+' with slow down of '+slowDown().toFixed(0));
chrome.tabs.executeScript(tab.id, {file: 'profile.js'});
})
};
function slowDown()
{
//console.log(' Slowdown: last interval '+ (new Date().getTime()-timeOfLastRequest)+' milisec.')
if (new Date().getTime()-timeOfLastRequest>minDelay)
{
console.log(' Previous Delay Greater Than Minimum Delay, Resetting Speed Count');
sendCount=1;
timeOfFirstRequest=new Date().getTime(); //else forget about it, reset time of first request
}
elapsedTime=new Date().getTime()-timeOfFirstRequest;
avgSpeed = elapsedTime/sendCount;
//console.log(" Started @ "+timeOfFirstRequest+" Current time "+new Date().getTime()+" Avg time fr 1st HTTPRequest "+avgSpeed.toFixed(0)+' milisec over '+sendCount+' Req');
if (avgSpeed<minDelay)
{
//console.log(" Delaying request by "+((minDelay-avgSpeed).toFixed(0))+" milisecs");
return minDelay-avgSpeed;
}
else
{
//console.log(' No Delay on Request');
return 1;
}
};
**未來建議**下一次提供最少的代碼量,以幫助您解決問題。你已經附加了太多的代碼。很多想嘗試幫助你的人可能會拒絕,因爲代碼量太多了(包括那些被註釋掉的日誌記錄調用)。 –