Whether it's window.settimeout or window.setinterval, you can't take arguments with a function name as a calling handle, and you need to take parameters on many occasions, which requires a workaround.
For example, for the function Hello (_name), it is used to display welcome information for the user name:
Copy Code code as follows:
var username= "Tony";
Show welcome information based on user name
function Hello (_name) {
Alert ("Hello," +_name);
}
At this point, it is not feasible to use the following statement to delay execution of the Hello function by 3 seconds:
Window.settimeout (Hello (userName), 3000);
This will cause the Hello function to execute immediately and pass the return value as the call handle to the SetTimeout function, and the result is not what the program needs. Using a string form can achieve the desired result:
Window.settimeout ("Hello (userName)", 3000);
The string here is a JavaScript code, where the username represents the variable. But this is not intuitive, and some occasions must use the function name, the following with a small trick to implement the call with a parameter function:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
var username= "Jack";
Show welcome information based on user name
function Hello (_name) {
Alert ("Hello," +_name);
}
Creates a function that returns a parameterless function
function _hello (_name) {
return function () {
Hello (_name);
}
}
Window.settimeout (_hello (userName), 3000);
This can also be written as window.settimeout (function () {return Hello (userName)}, 3000);
You no longer have to define function _hello ()
-->
</script>
This defines a function _hello, which receives a parameter and returns a function with no arguments, which uses the arguments of the external function inside the function to invoke it without using parameters. In the Window.settimeout function, use the _hello (userName To return a function handle with no parameters, thus enabling the function of parameter passing.