小程序定时器代码示例
下面是一个简单的例子,,后面显示最核心的代码片段
// components/countDown/countDown.js
Component({
/**
* 组件的属性列表
*/
properties: {
startTime: {
type: String,
value: ''
},
endTime: {
type: String,
value: ''
}
},
lifetimes: {
attached: function () {
// 在组件实例进入页面节点树时执行
// console.log(this.data)
let now = new Date().valueOf() / 1000;
let start = new Date(this.properties.startTime).valueOf() / 1000;
let end = new Date(this.properties.endTime).valueOf() / 1000;
this.setData({
Maintain_time: now < start ? (start - now) : (now < end ? end - now : 0)
})
if (now > start) {
this.setData({
display: 1
})
}
this.mytime();
},
detached: function () {
// 在组件实例被从页面节点树移除时执行
this.destroyed();
},
},
/**
* 组件的初始数据
*/
data: {
TIME: "0天0时0分0秒", //用于显示的值
display: 0,
d: '0',
h: '00',
m: '00',
s: '00',
Maintain_time: '', // 用于实际计算使用的倒计时
t: "", //定时器富于的变量。关闭页面要销毁,
},
/**
* 组件的方法列表
*/
methods: {
mytime: function () {
let that = this;
// this.setData({
setInterval(this.countTime, 1000, that)
// })
},
countTime: function (that) {
// console.log(that);
let time = that.data.Maintain_time;
// console.log(time)
if (time > 0) {
let d, h, m, s;
d = parseInt(time / 60 / 60 / 24);
h = parseInt((time / 60 / 60) % 24);
m = parseInt((time / 60) % 60);
s = parseInt(time % 60);
// console.log(d, h, m, s);
let tmpTime = (that.data.Maintain_time) - 1;
// console.log(tmpTime);
that.setData({
Maintain_time: tmpTime,
d: (d.toString().length == 1 ? '0' + d : d),
h: (h.toString().length == 1 ? '0' + h : h),
m: (m.toString().length == 1 ? '0' + m : m),
s: (s.toString().length == 1 ? '0' + s : s),
})
}
},
destroyed() {
clearInterval(this.data.t);
},
}
})
核心代码
//time 秒 是毫秒级别/1000 正确的时间戳格式 可以使用 ValueOf()进行转换
d = parseInt(time / 60 / 60 / 24);
h = parseInt((time / 60 / 60) % 24);
m = parseInt((time / 60) % 60);
s = parseInt(time % 60);