将 JavaScript 倒计时秒数转换为小时/分钟/秒。

3
我需要更改以下代码,使函数createTimer接收两个参数(小时和分钟),输出格式必须为“小时 分钟 秒”,我无法解决这个问题。
function createTimer(options) {
  var timer,
    instance = this,
    seconds = options.seconds,
    updateStatus = options.onUpdateStatus || function () {},
    counterEnd = options.onCounterEnd || function () {};

  function decrementCounter() {
    updateStatus(seconds);
    if (seconds === 0) {
      counterEnd();
      instance.stop();
    }
    seconds--;
  }

  this.start = function () {
    clearInterval(timer);
    timer = 0;
    seconds = options.seconds;
    timer = setInterval(decrementCounter, 1000);
  };

  this.stop = function () {
    clearInterval(timer);
  };
}

function startTimer() {
  var timer = new createTimer({
    seconds: 10,
    onUpdateStatus: function (seconds) {
      document.getElementById("timer").innerHTML = seconds + " seconds";
    },
    onCounterEnd: function () {
      document.getElementById("timer").innerHTML = "Time's up";
    },
  });
  timer.start();
}

那么你的问题是什么?将秒转换为小时和分钟吗? - derpirscher
不,我在不改变“startTimer”函数的情况下使用“小时和分钟”作为参数时遇到了问题。我的意思是,我能这样做吗,还是我必须重新编写所有代码?这里的“选项”是一个对象,对吧?我是初学者,需要一些提示。 - chris09trt
你只需要更改输出还是需要更改输入参数,以便createTimer函数接受小时和分钟而不是秒? - derpirscher
两者都需要。输出必须是“小时、分钟和秒”,同时createTimer函数需要接受小时和分钟作为参数。 - chris09trt
1个回答

1
你需要不断减少秒数,并使用多个if条件从分钟和小时中减去一秒。

function createTimer(hours, minutes) {
  var timer,
    instance = this,
    seconds = 0,
    hours = hours,
    minutes = minutes,
    updateStatus = onUpdateStatus || function() {},
    counterEnd = onCounterEnd || function() {};

  function onUpdateStatus(h, m, seconds) {
    document.getElementById("timer").innerHTML = h + " hours " + m + " minutes " + seconds + " seconds";
  }

  function onCounterEnd() {
    document.getElementById("timer").innerHTML = "Time's up";
  }

  function decrementCounter() {
    updateStatus(hours, minutes, seconds);
    if (hours === 0 && minutes === 0 && seconds === 0) {
      counterEnd();
      instance.stop();
    }
    seconds--;
    if (seconds < 0) {
      seconds = 59;
      minutes--;
      if (minutes < 0) {
        hours--;
        minutes = 59;
      }
    }

  }

  this.start = function() {
    clearInterval(timer);
    timer = 0;
    seconds = seconds;
    timer = setInterval(decrementCounter, 1000);
  };

  this.stop = function() {
    clearInterval(timer);
  };
}

function startTimer() {
  var timer = new createTimer(0,1);
  timer.start();
}

startTimer()
<div id="timer"></div>


是的,我考虑过这个问题,但是我的函数仍然没有将“小时和分钟”作为参数。它仍然将“选项”对象作为参数。 - chris09trt
@chris09trt,请查看已更新的回答。 - TechySharnav
还不太好:D,我忘了说......它只需要获取两个参数(小时/分钟),而不是更多。我可以随意更改createTimer函数中的内容,但不能更改startTimer函数。这就是为什么我有点困惑,这是一个棘手的问题。 - chris09trt
1
@chris09trt 连秒参数也没有? 如果您想让 createTimer 仅接受这两个参数,则需要将 onCounterEndonUpdateStatus 函数从 startTimer 中迁移。 - TechySharnav
嗯...你能给我看一下吗?我还是很困惑 :/ - chris09trt
@chris09trt 现在检查一下... - TechySharnav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接