js 实现时分秒倒计时

        let timeId2 =null;
        function countTime(lastTime) {
            //获取当前时间  
            let date = new Date();  
            let now = date.getTime();  
            //设置截止时间  
            let endDate = new Date(lastTime); 
            let end = endDate.getTime();  
            //时间差  
            let leftTime = end-now; 
            //定义变量,h,m,s保存倒计时的时间
            let h, m, s;
            if (leftTime >= 0) {
                h = Math.floor(leftTime / 1000 / 60 / 60);
                m = Math.floor(leftTime / 1000 / 60 % 60);
                s = Math.floor(leftTime / 1000 % 60);
                if(h < 10){
                    document.getElementById("_h").innerHTML = "0";
                    document.getElementById("_h2").innerHTML = h;
                }
                else{
                    document.getElementById("_h").innerHTML = Math.floor(h / 10);
                    document.getElementById("_h2").innerHTML = h % 10;
                }
                if(m < 10){
                    document.getElementById("_m").innerHTML = "0";
                    document.getElementById("_m2").innerHTML = m;
                }
                else{
                    document.getElementById("_m").innerHTML = Math.floor(m / 10);
                    document.getElementById("_m2").innerHTML = m % 10;
                }
                if(s < 10){
                    document.getElementById("_s").innerHTML = "0";
                    document.getElementById("_s2").innerHTML = s;
                }
                else{
                    document.getElementById("_s").innerHTML = Math.floor(s / 10);
                    document.getElementById("_s2").innerHTML = s % 10;
                }
            } else {
                document.getElementById("_h").innerHTML = "0";
                document.getElementById("_h2").innerHTML = "0";
                document.getElementById("_m").innerHTML = "0";
                document.getElementById("_m2").innerHTML = "0";
                document.getElementById("_s").innerHTML = "0";
                document.getElementById("_s2").innerHTML = "0";
                clearInterval(timeId2)
            }
        }
        //注意时间会有误差所以是每1050毫秒掉一次
        let lastTime = 200000 +(+new Date());
        timeId2 = setInterval(()=>{
            countTime(lastTime)
        },1050)

你可能感兴趣的:(js 实现时分秒倒计时)