javascript setTimeout不能识别函数参数

javascript setTimeout does not recognize function parameter

本文关键字:函数 参数 识别 不能 setTimeout javascript      更新时间:2023-09-26

我正在写一个Google Chrome扩展。我使用setTimeout来降低对服务器的请求速度。但是setTimeout没有像预期的那样工作。它返回一个错误,说reqUrl没有定义。

基于对类似问题的答案,似乎这是一个超出范围的问题,我不明白如何解决它,除了使reqUrl成为一个全局变量,这似乎不是一个很好的解决方案。如果我去掉括号,它就会失去控制,完全没有时间延迟。

如何使这个工作?

下面是代码。我包含了slowdown函数,尽管我不认为它是问题的核心。

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;
    }
};

setTimeout ({functionname},{超时},{param1}, {param2}…)

例子
setTimeout(callMe, 1000, 'say','hello');
function callMe(p1, p2){
alert(p1+" "+p2); //alerts say hello
}
function openDetailPg(reqUrl)
{
    console.log('openDetailPg at '+reqUrl);
    setTimeout(function(){createDetailWindow(reqUrl)},slowDown());
    ++sendCount;
    timeOfLastRequest=new Date().getTime();
};

您需要使用匿名函数,例如:

setTimeout(function(){createDetailWindow(reqUrl)},slowDown());

试一下:

setTimeout(function() { createDetailWindow(reqUrl); }, slowDown()); 

试试这个:

setTimeout(function(){ createDetailWindow(reqUrl) },slowDown());

你正在执行的JavaScript将看起来像这样:createDetailWindow(reqUrl),这实际上不是你想要的——你试图传递最初传递给openDetailPg的字符串,对吗?所以你传递给setTimeout的字符串需要适当地构造:"createDetailWindow('" + reqUrl + "')"(假设reqUrl总是被正确转义)。

顺便说一句,最好把东西浓缩成一个scscce,我花了一段时间才找到对setTimeout的调用。