4

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;
    }
};
1
  • 2
    Future advice Next time provide the least amount of code to help you solve the problem. You've attached way too much code. Many people that would try to help you may turn away because the amount of code is simply overwhelming (including those commented out logging calls). Commented Sep 15, 2011 at 14:34

6 Answers 6

4

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

example

setTimeout(callMe, 1000, 'say','hello');
function callMe(p1, p2){
alert(p1+" "+p2); //alerts say hello
}
Sign up to request clarification or add additional context in comments.

Comments

3
function openDetailPg(reqUrl)
{
    console.log('openDetailPg at '+reqUrl);
    setTimeout(function(){createDetailWindow(reqUrl)},slowDown());
    ++sendCount;
    timeOfLastRequest=new Date().getTime();
};

Comments

3

You need to use anonymous function for that, for example:

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

2 Comments

this works quite nicely. thanks. but why is it necessary to use an anonymous function here? i understand it solves the scope problem but i don't understand why.
There is several ways to do that. setTimeout function at first param expects handler of function or string. If string passed it works exactly like eval function but with closure so variable passed in that string is undefined. When you pass simple handler setTimeout calls that handler. And when you pass anonymous function setTimeout thinks that you pass handler. With closure you can see your variables inside anonymous function if the were declared before. But in general you can pass anything to anonymous function: function(){var test=test2+test3;for(var i=0;i<5;i++)...} everything :)
2

Try it like this:

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

Comments

2

Try this:

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

Comments

0

The JavaScript you're executing will look like this: createDetailWindow(reqUrl), which isn't actually what you want--you're trying to pass the string originally passed in to openDetailPg, right? So the string you're passing to setTimeout needs to be constructed appropriately: "createDetailWindow('" + reqUrl + "')" (assuming reqUrl will always be properly escaped).

Btw, it's best to condense stuff down to an sscce, it took me awhile just to find the call to setTimeout.

7 Comments

(The other answers using a closure are much, much cleaner than mine.)
passing strings to setTimeout is rather obsolete functionality.
Hence my follow-up comment. Mine, however, actually explains why the OP is seeing the error.
While you guys are busy thinking about my screwy code, maybe someone could explain to me why it runs out of control when the parenthesis are removed?
Because in the second example you're executing createDetailWindow and returning its result to setTimeout. setTimeout expects a function argument (or a string, but as pointed out, ew). That's why all the examples pass in an anonymous function including the reqUrl parameter.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.