The Javascript timer invokes the method of passing parameters, which the friend needs can refer to below.
Whether it is window.settimeout or window.setinterval, you cannot take arguments with the function name as the invocation handle, and in many cases it is necessary to take the parameter, which needs to be resolved by the method.
For example, function hello (_name), which is used to display a welcome message for a user name:
Copy the code code as follows:
var username= "Tony"; Displays the welcome message according to the user name function Hello (_name) {alert ("Hello," +_name);}
At this point, it is not feasible to attempt to use the following statement to delay the Hello function for 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 required by the program. You can achieve the desired result by using a string form:
Window.settimeout ("Hello (userName)", 3000);
The string here is a piece of JavaScript code, where username represents a variable. But this is not intuitive, and some occasions must use the function name, following a small trick to implement the call with the parameter function:
Copy the code code as follows:
<script language= "JavaScript" type= "Text/javascript" > <!--var username= "Jack"; Displays the welcome message according to the user name function Hello (_name) {alert ("Hello," +_name);}//Create a function to return a parameterless 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 don't have to define function _hello ()//--> </script>
This defines a function _hello, which receives a parameter and returns a function with no parameters, using the parameters 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 without parameters, which implements the function of parameter passing.