可以't传递匿名函数的参数,该参数作为setTimeout函数传递

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

本文关键字:参数 函数 setTimeout 可以      更新时间:2023-09-26

我在将值传递给匿名函数的参数时遇到问题,该函数作为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
        );
    }

您期望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
    );
}

不要传递它,您正在取消它http://jsfiddle.net/5cckcrhj/

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