vue中使用JS实现倒计时功能

一、倒计时功能

将剩余的时间显示出来,反馈给用户,每过1s,剩余的时间也减少1s

二、html中

<div style="position: fixed; top: 0; right:0; color:red">
        <span class="el-icon-time">{{ timeDay }}m{{ time }}s</span>
</div>

三、javascript中

//vue的data      
  data() {
    return {
      newTime: '2020-9-21 16:12:00',
      timeOut: '',
      timeSave: '',
      time: '',
      timeDay: ''
    }
  }
//method中的方法
setTime() {
      this.timeOut = setInterval(() => {
        setTimeout(() => {
          //newtime是倒计时的结束时间,当前时间和newTime指定的时间相同时,倒计时为0,即倒计时结束
          const timedate = new Date(this.newTime)
          const now = new Date()
          const date = timedate.getTime() - now.getTime()
          const time = Math.ceil(date / 1000) % 60
          const timeDay = Math.ceil(date / (1000 * 60)) - 1
          this.time = time > 0 ? time : 0
          this.timeDay = timeDay > 0 ? timeDay : 0
        }, 0)
      }, 1000)
    },

posted @ 2020-10-07 14:57  bkmemory  阅读(2856)  评论(0编辑  收藏  举报