First, let’s look at the usage of timers
1. setInterval(code,millisec[,"lang"]) The setInterval() method can call functions or calculate expressions according to the specified period (in milliseconds).
参数 |
描述 |
code |
必需,要调用的函数或要执行的代码串。 |
millisec |
必需,周期性执行或调用 code 之间的时间间隔,以毫秒计。 |
2.setTimeout(code,millisec) The setTimeout() method is used to call a function or calculate an expression after a specified number of milliseconds.
参数 |
描述 |
code |
必需,要调用的函数后要执行的 JavaScript 代码串。 |
millisec |
必需,在执行代码前需等待的毫秒数。 |
Tip: setTimeout() only executes code once. If you want to call it multiple times, use setInterval() or have the code itself call setTimeout() again.
Perhaps you have encountered such a problem. Whether it is setInterval() or setTimeout(), when a function with parameters is placed in the code parameter, the timer will fail. Take a look at the following example:
function test(str){
alert(str);
}
var a = "abcde"
setTimeout(test(a),3000);
When the above code is executed, the page will not delay calling test(a) for 3 seconds, but will Execute test(a) immediately. This problem will occur under IE, FF, and Chrome. If you often use timers, you should encounter this problem often, so how to solve it?
The author summarizes two commonly used solutions here. Of course, there should be other solutions, so I won’t go into details here.
Method 1: Wrap
function test (str){
alert(str);
}
var a = "abcde"
setTimeout(function(){
test(a);
},3000);
Method 2: Wrap the function to be called in quotes
function test(str){
alert(str);
}
var a = "abcde"
setTimeout("test(' a ')",3000) ;
The above only takes setTimeout() as an example, setInterval() is also applicable, so I won’t go into details here.