简体   繁体   中英

Get return value after SetTimeout

I've just asked about calling functions by name, now I want to process return statement after 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);
}

setTimeout works 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?

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

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

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

The setTimeout is asynchronous, which means that the ECall will return before the setTimeout code is invoked.

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 .

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

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