最近要实现一个列表倒计时的功能,写了个demo
展示图
<view class="center colu"> <view class="time" wx:for='{{list}}' style="color:{{item.color}}">{{item.show_time}}</view> </view>
Page({ /** * 页面的初始数据 */ data: { list: [] }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { let datas = []; let current = new Date().getTime() / 1000;for (let i = 0; i < 5; i++) { datas.push({}) } for (let i in datas) { let color = this.randomColor(); let random = Math.random().toFixed(2) * 10000; datas[i].timer = setInterval(() => { //截止时间 let time = current + random; time--; let now = new Date().getTime(); let diff = parseInt(time - now / 1000); if (diff < 0) { let list = this.data.list; clearInterval(list[i].timer) this.setData({ list }) } else { let date = this.formattime(diff * 1000); datas[i].show_time = date; datas[i].color = color; this.setData({ list: datas }) } }, 1000) } }, randomColor() { var r = Math.floor(Math.random() * 256); var g = Math.floor(Math.random() * 256); var b = Math.floor(Math.random() * 256); return "rgb(" + r + ',' + g + ',' + b + ")"; }, formattime(time) { var leave1 = time % (24 * 3600 * 1000) //计算小时 var hour = Math.floor(leave1 / (3600 * 1000)) var leave2 = leave1 % (3600 * 1000) //计算分钟 var minute = Math.floor(leave2 / (60 * 1000)) var leave3 = leave2 % (60 * 1000) //计算秒 var second = Math.round(leave3 / 1000) == '60' ? '00' : Math.round(leave3 / 1000) return [hour, minute, second].map(this.formatNumber).join(':') }, formatNumber(n) { n = n.toString() return n[1] ? n : '0' + n }, })