我正在编写谷歌浏览器扩展程序。我使用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;
}
};
**未来建议**下一次提供最少的代码量,以帮助您解决问题。你已经附加了太多的代码。很多想尝试帮助你的人可能会拒绝,因为代码量太多了(包括那些被注释掉的日志记录调用)。 –