setTimeout和setInterval
每种框架运行环境中都有特定的计划调度,那么js和Node.js环境下的计划调度就不得不说setTimeout和setInterval。
# 定时器setTimeout
定时执行,只执行一次
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
1
参数
# func|code
func指的是你需要定时执行的函数;code指需要运行的js字符串,code的执行原理同eval(),该操作有风险不建议使用
# delay
延迟毫秒数,默认为0毫秒。但因为js引擎中的任务队列和函数嵌套所以会存在一个最小延时,最小间隔是4ms。
# arg
附加参数,执行时会作为参数传递给func
# 示例
function delayAlert(arg1) {
alert('alert' + arg1);
}
// 使用函数引用或匿名函数
setTimeout(delayAlert, 1000, 'hello');
// 执行字符串(不建议)
setTimeout('alert("hello")');
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 计时器setInterval
使用方式同setTimeout,只是setTimeout是执行一次而setInterval是计时循环执行
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
1
# clearTimeout和clearInterval
使用setTimeout和setInterval都会返回一个标识,使用对应的clearTimeout和clearInterval可以提前取消计划调度
let timeOutId = setTimeout(...);
// 使用clearTimeout取消定时调度
clearTimeout(timeOutId);
let intervalId = setInterval(...);
// 使用clearInterval取消计时调度
clearInterval(timeOutId);
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 循环setTimeout替换setInterval
周期性循环调度可以使用setInterval也可以使用嵌套setTimeout的方式,如下:
function intervalT() {
// dosomething
}
// 使用setInterval
setInterval(intervalT, 500);
// 使用setTimeout
setTimeout(() => {
intervalT();
setTimeout(intervalT, 500);
}, 500);
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
使用setTimeout比setInterval更加灵活,我们可以通过上一次运行反馈进行下一步操作调整
setTimeout(() => {
let res = intervalT();
// res.....
let interval = 500;
if(res.temp) {
// interval = ....
}
setTimeout(intervalT, interval);
}, 500);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
上次更新: 2025/09/05, 8:09:00