Whether it is window.setTimeout or window.setInterval, you cannot take parameters when using the function name as the calling handle. In many cases, you must take parameters, so you need to find a way to solve it.
For example, for the function hello(_name), It is used to display the welcome message for the username:
var userName ="Tony";
//Display welcome message based on user name
function hello(_name){
alert("hello," _name);
}
At this time, it is not feasible to use the following statement to delay the execution of the hello function for 3 seconds:
window.setTimeout(hello(userName),3000);
This will cause the hello function to execute immediately and return The value is passed to the setTimeout function as a call handle, and the result is not what the program needs. The desired result can be achieved by using the string form:
window.setTimeout("hello(userName)",3000);
here The string is a piece of JavaScript code, in which userName represents a variable. However, this way of writing is not intuitive enough, and in some cases function names must be used. Here is a little trick to call a function with parameters:
A function _hello is defined here to receive a parameter and Returns a function without parameters. The parameters of the external function are used inside this function, so that it can be called without using parameters. In the window.setTimeout function, use _hello(userName) to return a function without parameters. handle, thus realizing the function of parameter passing.