W3Q
W3Q

Reputation: 909

can't pass an argument of anonymous function that is passed as setTimeout function

I'm having a trouble to pass a value to argument of anonymous function which is passed as an argument of setTimeout function.

I've been stuck for more than 5 hours already...

Please take a look at the code below and give me a help.

Thanks in advance!!

    if (_que.length > 0){

        var nextUrl = _shiftNextUrlFromQue();

        //here, the value for nextUrl exists.the value is url string.
        console.log(nextUrl); 


        setTimeout(function(nextUrl) {

            //here, the value is undefined.
            _analyzeUrl(nextUrl);


            }, 10000
        );

    }

Upvotes: 0

Views: 38

Answers (2)

Augusto Altman Quaranta
Augusto Altman Quaranta

Reputation: 1576

You are expecting nextUrl as an argument to the setTimeout callback function. That variable is defined in the parent function scope and there is the value you need.

The correct code would've been:

if (_que.length > 0) {

    var nextUrl = _shiftNextUrlFromQue();

    //here, the value for nextUrl exists.the value is url string.
    console.log(nextUrl); 


    setTimeout(function() { //HERE!... the timeout callback function has no argument

        _analyzeUrl(nextUrl);


        }, 10000
    );

}

Upvotes: 1

Popnoodles
Popnoodles

Reputation: 28409

Don't pass it, you're nullifying it http://jsfiddle.net/5cckcrhj/

setTimeout(function() {
     _analyzeUrl(nextUrl);
}, 10000

Upvotes: 0

Related Questions