Whether it is window. setTimeout or window. setInterval, parameters cannot be included when using the function name as the call handle. In many cases, parameters must be included, which requires a solution.
For example, for the hello (_ name) function, it is used to display the welcome information for the user name:
Copy codeThe Code is as follows:
Var userName = "Tony ";
// Display the welcome information based on the user name
Function hello (_ name ){
Alert ("hello," + _ name );
}
At this time, if you attempt to use the following statement to delay the hello function execution by 3 seconds, it is not feasible:
Window. setTimeout (hello (userName), 3000 );
This will enable the hello function to be executed immediately, and pass the returned value to the setTimeout function as the call handle. The result is not required by the program. The desired result can be achieved using a string:
Window. setTimeout ("hello (userName)", 3000 );
The string here is a piece of JavaScript code, where userName represents a variable. however, this method is not intuitive enough, and function names must be used in some cases. Here is a tips to call a function with parameters:
Copy codeThe Code is as follows:
<Script language = "JavaScript" type = "text/javascript">
<! --
Var userName = "jack ";
// Display the welcome information based on the user name
Function hello (_ name ){
Alert ("hello," + _ name );
}
// Create a function to return a non-Parameter Function
Function _ hello (_ name ){
Return function (){
Hello (_ name );
}
}
Window. setTimeout (_ hello (userName), 3000 );
// You can also enter window. setTimeout (function () {return hello (userName)}, 3000) here );
// No need to define function _ hello ()
// -->
</Script>
A function _ hello is defined here, which is used to receive a parameter and return a function without a parameter. An external function parameter is used inside the function to call it, no parameters are required. in window. in the setTimeout function, _ hello (userName) is used to return a function handle without parameters, thus implementing the parameter passing function.