Home  >  Article  >  Web Front-end  >  Javascript timer calls the method of passing parameters_javascript skills

Javascript timer calls the method of passing parameters_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:41:56924browse

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:

Copy the code The code is as follows:

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:
Copy code The code is as follows:



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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn