Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setTimeout does not recognize function parameter

I am writing a Google Chrome Extension. I use setTimeout to slowdown the speed of requests to the server. But setTimeout is not working as expected. It returns an error saying reqUrl is not defined.

Based on answers to similar questions on stackoverflow it appears this is an out of scope problem and I don't understand how to solve it except to make reqUrl a global variable which just doesn't seem a very good solution. If I remove the parenthesis, it just runs out of control, with no time delay at all.

How to make this work?

Here is the code. I've included the slowdow function although I don't think it is central to the problem.

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;
    }
};
like image 939
jeromekjerome Avatar asked Dec 10 '22 06:12

jeromekjerome


2 Answers

setTimeout({functionname}, {timeout}, {param1}, {param2}...)

example

setTimeout(callMe, 1000, 'say','hello');
function callMe(p1, p2){
alert(p1+" "+p2); //alerts say hello
}
like image 141
mooglife Avatar answered Jan 31 '23 05:01

mooglife


function openDetailPg(reqUrl)
{
    console.log('openDetailPg at '+reqUrl);
    setTimeout(function(){createDetailWindow(reqUrl)},slowDown());
    ++sendCount;
    timeOfLastRequest=new Date().getTime();
};
like image 23
Andrew D. Avatar answered Jan 31 '23 06:01

Andrew D.