一、延时函数
在实际开发中,我们可能会延时执行某一个操作,比如主页加载完之后,延时 n 秒弹出广告,这个时候我们就需要用到延时函数啦。
1. 语法形式
语法形式:
setTimeout(callback, delay);
语法解读:
callback:回调函数,延迟时间结束之后调用的函数delay:延迟时间,单位ms
2. 代码示例
console.log("登陆中, 请稍后...");
setTimeout(function(){
console.log("欢迎木子李!");
}, 2000);
console.log("...");
登陆中, 请稍后...
...
欢迎木子李!
注意:延时函数为异步操作,不会阻塞线程。
3. 取消延时
在延时的过程中,有时因为某种情况,不执行延时函数了,那么我们就需要取消延时,语法如下:
clearTimeout(t)
代码示例:
console.log("登陆中, 请稍后...");
// 定义变量记录延时函数
var t = setTimeout(function(){
console.log("欢迎木子李!");
}, 5000);
console.log("...");
// 清除延时函数
clearTimeout(t);
// 登陆中, 请稍后...
// ...
二、定时器
在实际开发中,如果我们需要每隔一段时间就做某个事情的时候,我们可以使用定时器,比如在做倒计时功能的时候就可以用到定时器函数。
1. 语法形式
语法形式:
setInterval(callback, interval);
语法解读:
callback:回调函数,每隔指定时间都会执行一次回调函数interval:时间间隔,单位ms
2. 代码示例
var count = 10;
setInterval(function() {
console.log(--count);
}, 1000);
上述代码,每隔1秒钟就会让 count 变量自减 1 并输出。
3. 清除定时器
清除定时器和清除延时函数一样,只需使用 clearInterval() 函数即可。
var count = 5;
// 定义变量存储定时器
var t = setInterval(function() {
if(count == 0) {
console.log("时间到!");
// 清除定时器
clearInterval(t);
return;
}
console.log(--count);
}, 1000);
三、扩展:倒计时
思路:
-
时间差计算(
ms):目标时间 - 当前时间 -
将时间差(
ns)转换为天、时、分、秒:let day = Math.floor(ms / 1000 / 60 / 60 / 24); let hours = Math.floor(ms / 1000 / 60 / 60 % 24); let minutes = Math.floor(ms / 1000 / 60 % 60); let seconds = Math.floor(ms / 1000 % 60);
比如,呈现一个距离2022年春节的倒计时功能:
function format(n) {
return n < 10 ? '0' + n : n;
}
function calc(targetDate, callback) {
var d, ms, t;
t = setInterval(function () {
d = new Date();
ms = targetDate - d;
if (ms > 0) {
var day = format(Math.floor(ms / 1000 / 60 / 60 / 24));
var hours = format(Math.floor((ms / 1000 / 60 / 60) % 24));
var minutes = format(Math.floor((ms / 1000 / 60) % 60));
var seconds = format(Math.floor((ms / 1000) % 60));
callback({
day,
hours,
minutes,
seconds,
});
} else {
clearInterval(t);
}
}, 1000);
}
calc(new Date('2022/02/01'), function (r) {
console.log(
`距离2022年春节还有${r.day}天${r.hours}时${r.minutes}分${r.seconds}秒`
);
});