Both setTimeout and setInterval are timers in Javascript, which can specify a delay time before performing an operation. The difference is that setTimeout stops after executing an operation after the specified time, while setInterval can continue to loop.
In addition, setTimeout and setInterval can also pass parameters in the form of extension operators; now IE10 and above versions, and other mainstream browsers, are supported.
One. setTimeout use
The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds.
1.1 Syntax:
setTimeout(code, millisec)
1.2 Examples:
setTimeout(function(){
console.log('执行了...')
}, 1000);
1.3 setTimeout loop executes multiple times:
Since setTimeout is only executed once, the execution function can be run only if the conditions are met.
var index = 0;
function callback(){
//开始计时
setTimeout(function(){
//循环执行5次后,结束计时
if(index<5){
callback();
}
console.log('执行次数', index++);
}, 3000)
}
callback();
Output result:
1.4 Clear the setTimeout timer
Although the setTimeout timer is only executed once, in some special scenarios, it is necessary to terminate the timing function that is about to be executed. In this case, clearTimeout is required. For example, when Vue is developed, if the page is refreshed without feeling, if the previously defined execution function is not eliminated, repeated accumulation will occur; or after certain conditions are met, the previously defined execution function needs to be terminated. details as follows:
var index = 0,
handle = null;
function callback(){
clearTimeout(handle);
//开始计时
handle = setTimeout(function(){
//循环执行5次后,结束计时
if(index<5){
callback();
}
console.log('执行次数', index++);
}, 3000)
}
callback();
Second, the use of setInterval
The setInterval() method calls a function or evaluates an expression at a specified interval (in milliseconds).
The setInterval() method will keep calling the function until clearInterval() is called or the window is closed.
2.1 Grammar
setInterval(code, millisec)
2.2 Examples
Since setInterval sets the timing period, it will continue to execute, so when certain conditions are met, clearInterval is used to end the timing function. code show as below:
var index = 0,
handle = null;
function callback(){
//循环执行6次后,结束计时
if(index>=5){
clearInterval(handle);
}
console.log('执行次数', index++);
}
//开始计时
handle = setInterval(callback, 3000)
Output result:
3. The parameter passing function of setTimeout and setInterval
In addition to defining the execution function and execution cycle (milliseconds) in setTimeout and setInterval, you can also add parameter data in the form of extension operators, which is not covered in many documents.
3.1 setTimeout parameters
parameter | describe |
---|---|
func | required. The javascript code string to be executed can also be a function |
time | required. Execution period (milliseconds) |
param1, param2, ... | optional. Pass other parameters to the execution function |
grammar:
setTimeout(func, time, ...)
3.2 setInterval parameter
parameter | describe |
---|---|
func | must. The javascript code string to be executed can also be a function |
time | must. Execution period (milliseconds) |
param1, param2, ... | optional. Pass other parameters to the execution function |
grammar:
setInterval(func, time, ...)
3.2 Case
//传入参数a和b,计算求和
setTimeout(function(a, b){
console.log(a + '+' + b + '=' + (a+b));
}, 3000, 5, 10);
//传入参数a和b,计算总和,大于100终止
var total = 0,
handle = setInterval(function(a, b){
total += a + b;
console.log('total:', total);
if(total>100){
clearInterval(handle);
}
}, 3000, 10, 30);
Output result:
3.3 Add timer in for
Since the execution function of setTimeout is running, the for loop has already ended, so the value of i has been incremented to 5, so the execution results of the five timers are all 5.
//未通过定时器传入参数
for(var i = 0; i < 5; i++){
setTimeout(function(){
console.log('value:', i);
}, 2000*(i+1));
}
Output result:
//通过定时器会传入参数
for(var i = 0; i < 5; i++){
setTimeout(function(value){
console.log('value', value);
}, 2000*(i+1), i);
}
Output result:
4. Low version compatibility processing
In the lower version, the parameter passing function cannot be realized, and the same effect can be achieved by customizing, the code is as follows:
var _timeout = setTimeout;
//改写setTimeout定时器
window.setTimeout = function(callback, time){
//获取除callback和time以外的参数,并以数组形式返回
var args = Array.prototype.slice.call(arguments, 2);
//定义新的执行函数
var _cb = function(){
callback.apply(null, args);
}
//定义setTimeout定时器
_timeout(_cb, time);
}
//定义计时器
window.setTimeout(function(a, b){
console.log('a:'+a, 'b:'+b);
}, 1000, 5, 100);
Enter the result: