You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:36:02