//申明一个定时器
let endInterval;
//结束时间(毫秒数,这里是距离 1970 年 1 月 1 日至今的毫秒数)
let endSeconds;
//结束时间差
const ENDTIME = 10 * 1000;
???????window.onload = function () {
//当页面加载的时候,获取当前加载页面时刻的当前时间,再加上我们需要的倒计时间,注意这里全都是毫秒数,。
??????????? endSeconds= new Date().getTime() + ENDTIME;
??????????? //开始定时器
??????????? endInterval = setInterval(timeItev, 500);
???????}
???????function timeItev() {
??????????? //计算时间差,在定时器里面不停获取到新的new Date(),用end-new这个值就会一直变小
??????????? let nowDate=new Date(endSeconds - new Date().getTime());
??????????? //转化为分钟和秒钟
??????????? let min = nowDate.getMinutes();
??????????? let sec = nowDate.getSeconds();
??????????? //把时间设置到你需要的标签 上面
??????????? $("#time").html(`${min}:${sec}`)
??????????? if(min==0 && sec==0){
??????????????? clearInterval(endInterval)
??????????????? console.log("定时器结束")
??????????? }
???????}
js如何设置一个倒计时
原文地址:http://www.cnblogs.com/xiao-he-shang/p/7476329.html