js 实现 时分秒 倒计时

1. 实现效果

在这里插入图片描述

2. 实现原理

  1. 计算和显示的变量分离;h、m、s用于计算,均为0~59;h1、m1、s1用于显示;
  2. 设置定时器,让s每隔1秒减1
  3. 当s<0时,s=59,m=m-1
  4. 当m<0时,m=59,h=h-1
  5. 当h<0时,h=m=s=0,并清除定时器
  6. 当h、m、s小于10时,h1、m1、s1分别前面补0占位

3.代码

//时间差获取天时分秒
function getDHMS(str){
    str = new Date('2020-10-30 8:00')
    let sec = Math.round((new Date(str) - new Date())/1000);
    let date,h,m,s,ys;
    if(Math.floor(sec/(24*60*60))>=1){
        date = Math.floor(sec/(24*60*60));
        ys = sec%(24*60*60);
    }else{
        date = 0;
        ys = sec;
    }
    if( Math.floor(ys/(60*60)>=1)){
        h = Math.floor(ys/(60*60));
        ys = ys%(60*60);
    }else{
        h = 0;
        ys = ys;
    }
    if( Math.floor(ys/60)>=1){
        m = Math.floor(ys/60);
        ys = ys%60;
    }else{
        m = 0;
        ys = ys;
    }
    if(ys>0){
        s = ys;
    }else{
        s = 0
    }
    // console.log(date,h,m,s)
    return {
        date,h,m,s
    }
}
//时分秒 倒计时
function timechange(obj,ele,str){
    let {h,m,s} = obj;
    let time,s1,m1,h1;
    let timer = setInterval(function(){
        s--;
        if(s<0){
            s = 59;
            m--;
        }
        if(m<0){
            m = 59;
            h--;
        }
        if(h<0){
            h = m = s = 0;
            clearInterval(timer);
        }
        s1 = s<10?'0'+s:s;
        m1 = m<10?'0'+m:m;
        h1 = h<10?'0'+h:h;
        time = h1 + ' : ' + m1 + ' : ' + s1;
        ele.innerHTML = str+time;
        // console.log(time);
    },1000)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值