美文网首页
2020-11-11JavaScript实现00:00,00:0

2020-11-11JavaScript实现00:00,00:0

作者: gdlooker | 来源:发表于2020-11-11 09:28 被阅读0次

    示例代码如下:

    <template>
      <div class="counter-timer-row">
        <span>{{ cTime }}</span>
      </div>
    </template>
    <script>
    export default {
      name: "counterTimer",
      components: {},
      data() {
        return {
          cTime: "00:00",
        };
      },
      created() {
        this.startTimer();
      },
      methods: {
        startTimer() {
          let that = this;
          let lastTime = new Date().getTime();
          this.myTimer=setInterval(function () {
            //setInterval定时方法,每一秒执行一次,实现时钟效果
            let cTime=new Date().getTime()
            let xcTime=cTime-lastTime
            let rTime = that.formatDuring(xcTime);
            console.log('rTime',rTime)
            that.cTime=rTime
            //至此,时间输出为11:05:03正确格式,而非11:5:3
          }, 1000);
        },
        formatDuring(mss) {
          var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    
          var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    
          var seconds = (mss % (1000 * 60)) / 1000;
    
          hours = hours < 10 ? "0" + hours : hours;
    
          minutes = minutes < 10 ? "0" + minutes : minutes;
    
          seconds = seconds < 10 ? "0" + seconds : seconds;
    
          return hours + ":" + minutes + ":" + seconds;
        },
        //停止timer
        stopTimer(){
            if(!!this.myTimer){
               clearInterval(this.myTimer)
            }
        }
      },
    };
    </script>
    
    <style scoped="scoped">
    .counter-timer-row {
      display: flex;
      flex-direction: row;
      justify-content: center;
    }
    </style>
    

    相关文章

      网友评论

          本文标题:2020-11-11JavaScript实现00:00,00:0

          本文链接:https://www.haomeiwen.com/subject/oufebktx.html