简体   繁体   中英

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

    }

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

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM