如何修改JavaScript倒计时代码,使createTimer支持时分参数并输出时分秒格式
修改后完整实现
// 改造后支持传入小时、分钟参数的计时器 function createTimer(options) { var timer, instance = this, // 新增小时、分钟参数接收,默认值为0 hours = options.hours || 0, minutes = options.minutes || 0, // 自动将小时、分钟转换为总秒数计算,兼容原有seconds参数 totalSeconds = options.seconds || hours * 3600 + minutes * 60, updateStatus = options.onUpdateStatus || function () {}, counterEnd = options.onCounterEnd || function () {}; // 补零工具,小于10的数字统一显示为两位 function padZero(num) { return num < 10 ? '0' + num : num } function decrementCounter() { // 总秒数回算为小时、分钟、秒三个单位 const remainingHours = Math.floor(totalSeconds / 3600) const remainingMinutes = Math.floor((totalSeconds % 3600) / 60) const remainingSeconds = totalSeconds % 60 // 向回调传递三个时间单位值 updateStatus(padZero(remainingHours), padZero(remainingMinutes), padZero(remainingSeconds)) if (totalSeconds === 0) { counterEnd(); instance.stop(); } totalSeconds--; } this.start = function () { clearInterval(timer); timer = 0; // 初始化总秒数 totalSeconds = options.seconds || (options.hours || 0) * 3600 + (options.minutes || 0) * 60; timer = setInterval(decrementCounter, 1000); }; this.stop = function () { clearInterval(timer); }; } // 调用示例:设置1小时5分钟倒计时 function startTimer() { var timer = new createTimer({ hours: 1, minutes: 5, onUpdateStatus: function (hours, minutes, seconds) { // 输出格式为「小时 分钟 秒」 document.getElementById("timer").innerHTML = `${hours} ${minutes} ${seconds}`; }, onCounterEnd: function () { document.getElementById("timer").innerHTML = "Time's up"; }, }); timer.start(); }
核心改动说明
- 入参新增
hours、minutes两个字段,内部自动转换为总秒数做倒计时计算,兼容原有seconds参数的用法 - 每次倒计时更新时,会把剩余时间拆分为小时、分钟、秒三个值返回给
onUpdateStatus回调,自带补零逻辑保证显示格式统一 - 调用时按需传入小时和分钟,回调内直接拼接三个参数即可得到要求的输出格式
内容的提问来源于stack exchange,提问作者chris09trt
相关产品推荐
相关产品推荐

