无法传递作为setTimeout函数传递的匿名函数的参数

时间:2014-09-11 00:28:09

标签: javascript jquery

我很难将值传递给匿名函数的参数,该参数作为setTimeout函数的参数传递。

我已经被困了5个多小时......

请查看下面的代码并给我一个帮助。

提前致谢!!

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

    }

2 个答案:

答案 0 :(得分:1)

您期望 nextUrl 作为setTimeout回调函数的参数。该变量在父函数范围内定义,并且存在您需要的值。

正确的代码是:

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

}

答案 1 :(得分:0)

不要传递它,你将它取消http://jsfiddle.net/5cckcrhj/

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