javascript 获取 SetTimeout 后的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5211103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:23:19  来源:igfitidea点击:

Get return value after SetTimeout

javascriptfunctionevalreturnsettimeout

提问by Max Frai

I've just asked about calling functions by name, now I want to process returnstatement after SetTimeout:

我刚刚询问了按名称调用函数的问题,现在我想在以下之后处理return语句SetTimeout

function ECall(funcName, arg)
{
    command += "(";
    for (var i=1; i<arguments.length; i++) 
    {
        command += "'" + arguments[i] + "'";
        if (i != arguments.length-1) command += ',';
    }
    command += ")";

    //var funcPtr = eval(funcName);
    //return funcPtr(arg); // This works, but I need SetTimeout

    setTimeout('window[\'' + funcName + '\']' + command, 1000);
}

setTimeoutworks great, but I have to save return value of called function. When I write: setTimeout('alert(window[\'' + funcName + '\']' + command + ')', 1000);It alerts return value of function. How can I store it?

setTimeout效果很好,但我必须保存被调用函数的返回值。当我写:setTimeout('alert(window[\'' + funcName + '\']' + command + ')', 1000);它提醒函数的返回值。我怎样才能储存它?

采纳答案by Tim Down

You don't need to use any of this string manipulation. Just pass a function reference to window.setTimeout(). To store the returned value of the function, simply assign it to a variable in the function you pass to window.setTimeout()

您不需要使用任何这种字符串操作。只需将函数引用传递给window.setTimeout(). 要存储函数的返回值,只需将其分配给传递给的函数中的变量window.setTimeout()

var savedValue;

function ECall(funcName)
{
    var args = Array.prototype.slice.call(arguments, 1);
    var func = window[funcName];

    window.setTimeout(function() {
        savedValue = func.apply(this, args);
    }, 1000);
}

回答by user113716

If you wanted to return a value from ECall, it won't work.

如果您想从 返回一个值ECall,它将不起作用。

The setTimeoutis asynchronous, which means that the ECallwill return beforethe setTimeoutcode is invoked.

setTimeout是异步的,这意味着ECall将返回之前setTimeout调用代码。

Or if you wanted the alert()to be part of the setTimeout, you could pass an anonymous function. Also, it would be better to not pass a string to the setTimeout.

或者,如果您希望alert()成为 的一部分,则setTimeout可以传递一个匿名函数。此外,最好不要将字符串传递给setTimeout.

I'd do this instead:

我会这样做:

function ECall(funcName, arg)
{
       // Get an Array of the arguments, except for the first one.
    var args = Array.prototype.slice.call( arguments, 1 );

       // Pass an anonymous function that calls the global "funcName" function
       //    inside the alert(). 
       // It uses .apply() to pass the arguments we sliced.
    setTimeout( function() {
        alert( window[ funcName ].apply( window, args ) );
    }, 1000);
}