duidui_mini_program/pages/camp_task_text_image/modules/timer-utils.js
2026-03-27 10:41:46 +08:00

74 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 倒计时工具模块
* 负责倒计时的格式化和启动逻辑
*/
/**
* 格式化倒计时显示(秒数转为 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;
}
}