演示效果:
定时器
原理
通过开启一个定时器,每隔一秒执行一次获取当前时间的方法函数并实时渲染到前端页面。
一、格式化当前时间的方法
export const getTimeNow = () => {
let dateTime
let yy = new Date().getFullYear()
let mm = new Date().getMonth() + 1
let dd = new Date().getDate()
let hh = new Date().getHours()
let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() :
new Date().getMinutes()
let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() :
new Date().getSeconds()
dateTime = `${yy}-${mm}-${dd} ${hh}:${mf}:${ss}`;
return dateTime
}
通过调用Date()函数获取当前时间戳。使用模板字符串将获取到的年月日拼接成我们习惯的形式
二、XML代码
<!-- 显示时间 -->
<view class="time">
{{time}}
</view>
三、JavaScript代码
data: {
// 显示的时间
time:'',
// 定时器的开关
timer: ''
},
//页面首次加载会将时间赋给time
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
let that = this
that.setData({
time:getTimeNow()
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
const that = this
this.data.timer = setInterval(function(){
// 实时调用时间函数getTimeNow获取最新时间
const Time = getTimeNow()
that.setData({
time:Time
})
console.log("定时器还开着喔~~~");
},1000)
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
// 当关闭当前页面时关闭定时器,不然会一直开着,影响性能
clearInterval(this.data.timer)
},
注意点:
1、在 onReady()生命周期函数中当页面渲染完成即刻将获取到的当前时间赋给time值。在使用 this.setData()函数时,注意 this 的指向问题,需要将 that=this 。这样才不会报错
2、 在页面加载设置一个定时器,并使用 timer 定时器开关存储起来。
3、 在页面卸载函数中清除当前开启的定时器,不然会一直在执行。严重影响性能消耗
错误展示:
this.setData()函数报错,使用 that=this 重新指向。这是因为 this关键字的指向可能会发生变化,使用that=this的方式可以保存this的指向,确保在后续代码中能够正确访问和使用。
常见情况:在一个回调函数或异步操作中使用this.setData()时,this的指向会发生改变,指向的不是原来的上下文对象,导致无法正确执行setData()函数。
一定要在监听页面卸载函数中将定时器关掉,不然就算你退出当前页面他也一直在开着。