前端实现时间功能

188 阅读1分钟

功能描述:后台返回一个时间,前端实现秒表功能,并显示在浏览器上。

clipboard.png

html代码:

System Time:{{systemTime}}

js代码:

data(){ 
  return{ 
    timer:null;//定义一个定时器变量 
    time:'', 
    systemTime:''
  }
}
mounted(){ 
  const _this=this; 
  _this.getTime(); 
  document.addEventListener('visibilitychange',function(){ 
    if(document.hidden){ 
    //当页面切换或者隐藏时触发,可以用来清除定时器 
    clearInterval(_this.timer); 
    }else{ 
    //当页面重新被唤醒时触发,重新触发定时器 
    clearInterval(_this.timer); 
    _this.getTime(); 
    } 
  }) 
}
methods:{ 
  async getTime(){ 
    const res = await this.$api.getServerTime(); 
    this.time= res.data.resultData; //后端返回的时间 格式:2022-03-09 15:12:08 
    this.resTime(this.time); 
    this.timer=setInterval(()=>{ this.resTime(this.time); },1000); 
  } 

restTime(time){ 
  const comDate=(time)=>time.replace(/-/g,'/'); 
  var myDate = time instanceof Object ? time:typeof time ==='number'?new Date(time):new Date(comDate(time));
  var y = myDate.getFullYear(); 
  var M = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月) 
  var d = myDate.getDate(); //获取当前日(1-31) 
  var h = myDate.getHours(); //获取当前小时数(0-23) 
  var m = myDate.getMinutes(); //获取当前分钟数(0-59) 
  var s = myDate.getSeconds(); //获取当前秒数(0-59) 
  M = this.check(M); 
  d = this.check(d); 
  h = this.check(h); 
  m = this.check(m); 
  s = this.check(s); 
  var timestr = y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s; 
  this.systemTime = timestr; 
  this.time = new Date(myDate.getTime() + 1000); 
 } 

check(i){ 
  var num = i < 10 ? '0' + i : i; 
  return num; 
 } 
}

beforeDestroy() { 
  if (this.timer) { 
    clearInterval(this.timer); 
  } 
},

一些注意的点:

1.一开始没有加监听器,当用户切换标签再回到当前页面时,时间会延后,后来排查发现时浏览器为了节约资源,会自动延迟定时器的执行

解决方案: 使用visibilitychange

2.在IOS5以上的版本(不包含IOS5)中的safari浏览器能够正确解释出Javascript中的 new Date('2022-03-09') 的日期对象。但是在IOS5版本里面的Safari解释new Date('2022-03-09') 就不正确,在IOS5的Safari中返回的永远是"Invalid Date"。

解决方案: 因此要将后台返回的时间格式’2022-03-09‘转成斜线格式 time.replace(/-/g,'/')