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-开发者_JS百科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);
}
精彩评论