First look at the use of the timer
1. SetInterval (code,millisec[, "Lang"]) the SetInterval () method can call a function or a calculation expression in the specified period (in milliseconds).
Parameters |
Description |
Code |
Required, the function to invoke or the code string to execute. |
Millisec |
The time interval, in milliseconds, that is required to periodically execute or call code. |
The 2.setTimeout (code,millisec) settimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.
Parameters |
Description |
Code |
Required, the JavaScript code string to be executed after the function to be invoked. |
Millisec |
Required, the number of milliseconds to wait before executing the code. |
Tip: settimeout () executes only one code at a time. If you want to call more than once, use SetInterval () or let code itself call SetTimeout () again.
Maybe you've had this problem, whether it's setinterval () or settimeout (), when you put a parameter function in the code argument, the timer will fail, look at the following example:
Copy Code code as follows:
function Test (str) {
alert (str);
}
var a = "ABCDE"
settimeout (Test (a), 3000);
Execute the above code, the page will not delay 3 seconds to call Test (a), but will immediately execute test (a), IE, FF, Chrome will appear under the problem, if you often use the timer, this problem should often encounter, then how to solve it?
The author here summed up two commonly used solutions, of course, there should be other solutions, here is not to repeat.
Method 1: Wrapping with anonymous functions
Copy Code code as follows:
function Test (str) {
alert (str);
}
var a = "ABCDE"
settimeout (function () {
Test (a);
},3000);
Method 2: Enclose the function that you want to call
Copy Code code as follows:
function Test (str) {
alert (str);
}
var a = "ABCDE"
settimeout ("Test (' +a+ ')", 3000);
For example, the SetInterval () is settimeout (), and it is not described too much here.