【问题标题】:can't pass an argument of anonymous function that is passed as setTimeout function无法传递作为 setTimeout 函数传递的匿名函数的参数
【发布时间】:2014-09-11 08:42:59
【问题描述】:

我无法将值传递给作为 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
        );

    }

【问题讨论】:

  • 我很确定您甚至不需要将其作为参数传递给 setTimeout 中的函数...只需将参数留空即可:)
  • 感谢您的帮助!
  • 是的,回调的第一个参数是undefined,它会覆盖该上下文中的变量。
  • 那么,你的意思是这样吗? setTimeout(function() { _analyzeUrl(nextUrl); }, 10000 );
  • 哇!我懂了。我现在就去试试!

标签: javascript jquery


【解决方案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
    );

}

【讨论】:

  • OP 知道他们正在这样做。有什么问题?
  • 实际上,他没有传递参​​数。他确实期望回调函数中有一个参数(参数)setTimeout
【解决方案2】:

不要通过它,你正在取消它http://jsfiddle.net/5cckcrhj/

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 2011-05-11
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多