es6实现倒计时

1、思路如下

  1. 当前时间获取   
    let now=new Date().getTime();
  2. 截止日期 
    let date = new Date('2020');    //设置截止日期
    let end = date.getTime();   //这个日期要转换成时间戳
  3. 倒计时的日期
    let last_time=end-now;
  4. 判断now和end大小,如果now >end 倒计时就要截止了
  5. 时间转换成时分秒
    const px_d=1000*60*60*24;
    const px_h=1000*60*60;
    const px_m=1000*60;
    const px_s=1000;
    let d=Math.floor(last_time/px_d);
    let h=Math.floor((last_time-d*px_d)/px_h);
    let m=Math.floor((last_time-d*px_d-h*px_h)/px_m);
    let s=Math.floor((last_time-d*px_d-h*px_h-m*px_m)/px_s);
  6. 使用标签模板将值进行传递
  7. let html=`${d}天 ${h}时 ${m}分 ${s}秒`  //es6的标签模板是特别好用的 在vue项目等,都是使用标签模板进行传值

2、js代码如下

<script>
    {
        let countdown=()=>{
            let showtime=document.getElementById('showtime') 
            let now=new Date().getTime();
            let date = new Date('2020');
            let end = date.getTime();
            let last_time=end-now;
            if( now-end>0){
                alert('考研成功!!!');
            }else{
                const px_d=1000*60*60*24;
                const px_h=1000*60*60;
                const px_m=1000*60;
                const px_s=1000;
                let d=Math.floor(last_time/px_d);
                let h=Math.floor((last_time-d*px_d)/px_h);
                let m=Math.floor((last_time-d*px_d-h*px_h)/px_m);
                let s=Math.floor((last_time-d*px_d-h*px_h-m*px_m)/px_s);
                let html=`${d}天 ${h}时 ${m}分 ${s}秒`
                showtime.innerHTML = html;
               clearTimeout();
            }
        }
    setInterval(function () {
          countdown();
       },1000)
    }
</script>

版权声明:本文为weixin_41111987原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。