Products
GG网络技术分享 2025-11-13 05:53 2
在微信细小程序中实现倒计时的功Neng, Neng采用以下步骤:
先说说需要确定倒计时的开头时候和收尾时候。这Neng通过细小程序页面的 data 对象中的属性来设置。

setInterval 实现倒计时逻辑在页面的 onLoad 生命周期函数中, 用 setInterval 来设置一个定时器,每秒geng新鲜一次倒计时的值。
javascript
Page({
data: {
startTime: Date.now + 1000 * 60 * 60 * 24, // 虚假设倒计时从眼下起24细小时后开头
endTime: Date.now + 1000 * 60 * 60 * 48, // 虚假设倒计时持续48细小时
countDownDay: '',
countDownHour: '',
countDownMinute: '',
countDownSecond: '',
timer: null
},
onLoad: function {
this.startCountDown;
},
onUnload: function {
if {
clearInterval;
}
},
startCountDown: function {
let that = this;
that.data.timer = setInterval {
that.updateCountDown;
}, 1000);
},
updateCountDown: function {
let nowTime = Date.now;
let timeLeft = that.data.endTime - nowTime;
if {
clearInterval;
that.setData({
countDownDay: '00',
countDownHour: '00',
countDownMinute: '00',
countDownSecond: '00'
});
return;
}
let days = Math.floor);
let hours = Math.floor) / );
let minutes = Math.floor) / );
let seconds = Math.floor) / 1000);
that.setData({
countDownDay: that.formatTime,
countDownHour: that.formatTime,
countDownMinute: that.formatTime,
countDownSecond: that.formatTime
});
},
formatTime: function {
return time <10 ? '0' + time : time;
}
});
canvas 绘制倒计时为了搞优良倒计时的美观程度,Neng用 canvas 绘制倒计时数字和进度条。
javascript Page({ // ...其他代码 canvasId: 'countdownCanvas', canvasContext: null,
onLoad: function { this.startCountDown; this.drawCountDown; },
drawCountDown: function { let ctx = wx.createCanvasContext; let timeLeft = this.data.endTime - Date.now; if { ctx.setTextAlign; ctx.setFillStyle; ctx.setFontSize; ctx.fillText; ctx.draw; return; } let days = Math.floor); let hours = Math.floor) / ); let minutes = Math.floor) / ); let seconds = Math.floor) / 1000);
ctx.clearRect; // 清除画布
ctx.setTextAlign;
ctx.setFillStyle;
ctx.setFontSize;
ctx.fillText;
ctx.fillText;
ctx.fillText;
ctx.fillText;
ctx.draw;
} });
为了搞优良性Neng,Neng考虑以下优化措施:
- 用 onHide 和 onShow 生命周期函数来控制计时器的启动和暂停。
- 少许些频繁调用 setData 的次数, Neng用临时变量存储需要geng新鲜的数据,再说说一次性调用 setData。
- 用 requestAnimationFrame 来优化动画渲染。
这样,你就Neng在微信细小程序中实现一个美观且高大效的倒计时功Neng了。
Demand feedback