74 lines
1.6 KiB
JavaScript
74 lines
1.6 KiB
JavaScript
/**
|
||
* 倒计时工具模块
|
||
* 负责倒计时的格式化和启动逻辑
|
||
*/
|
||
|
||
/**
|
||
* 格式化倒计时显示(秒数转为 MM:SS 格式)
|
||
* @param {Number} seconds - 剩余秒数
|
||
* @returns {String} 格式化后的时间字符串
|
||
*/
|
||
export function formatTimer(seconds) {
|
||
if (seconds <= 0) return '00:00';
|
||
const mins = Math.floor(seconds / 60);
|
||
const secs = seconds % 60;
|
||
// 兼容 padStart(微信小程序可能不支持)
|
||
const formatNumber = (num) => {
|
||
return num < 10 ? '0' + num : String(num);
|
||
};
|
||
return formatNumber(mins) + ':' + formatNumber(secs);
|
||
}
|
||
|
||
/**
|
||
* 启动倒计时
|
||
* @param {Object} context - 页面上下文
|
||
* @param {Function} onComplete - 倒计时结束回调
|
||
* @returns {Number} 定时器ID
|
||
*/
|
||
export function startTimer(context, onComplete) {
|
||
if (context.timerInterval) {
|
||
clearInterval(context.timerInterval);
|
||
}
|
||
|
||
// 立即更新一次显示
|
||
context.setData({
|
||
timerText: formatTimer(context.data.remainingTime)
|
||
});
|
||
|
||
context.timerInterval = setInterval(() => {
|
||
const remainingTime = context.data.remainingTime - 1;
|
||
|
||
if (remainingTime <= 0) {
|
||
// 时间到
|
||
if (context.timerInterval) {
|
||
clearInterval(context.timerInterval);
|
||
context.timerInterval = null;
|
||
}
|
||
|
||
if (onComplete) {
|
||
onComplete();
|
||
}
|
||
return;
|
||
}
|
||
|
||
context.setData({
|
||
remainingTime,
|
||
timerText: formatTimer(remainingTime)
|
||
});
|
||
}, 1000);
|
||
|
||
return context.timerInterval;
|
||
}
|
||
|
||
/**
|
||
* 停止倒计时
|
||
* @param {Object} context - 页面上下文
|
||
*/
|
||
export function stopTimer(context) {
|
||
if (context.timerInterval) {
|
||
clearInterval(context.timerInterval);
|
||
context.timerInterval = null;
|
||
}
|
||
}
|
||
|