Get return value after SetTimeout

I just asked about calling functions by name, now I want to process the statement returnafter 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 fine, but I need to save the return value of the called function. When I write: setTimeout('alert(window[\'' + funcName + '\']' + command + ')', 1000); It warns about the return of the function value. How to save it?

+5
source share
2 answers

You do not need to use any of these string manipulations. Just pass the function link to window.setTimeout(). To save the return value of a function, simply assign it a variable in the function you pass towindow.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);
}
+5

ECall, .

setTimeout , , ECall setTimeout.

, , alert() setTimeout, . , setTimeout.

:

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

All Articles