Javascript 带用户输入的倒数计时器

Javascript Countdown Timer with User input

我正在尝试创建一个倒计时计时器,用户可以在其中输入天、小时、分钟和秒值的任意组合,并让它倒计时到完成。我觉得我已经掌握了所有的部分,但是在尝试解决这个问题一周之后,我需要帮助。我用不同的效果随机播放代码。基本上我觉得我缺少一种格式化输入数据的方法,我可以用这种方法从当前日期中减去,但老实说我不知道​​。任何输入都会有所帮助。

Javascript:

function start() {
  var countdownTimer = setInterval('timer()', 1000);
}

function timer() {
  var d = parseInt(document.getElementById("days").value, 0);
  var h = parseInt(document.getElementById("hours").value, 0);
  var m = parseInt(document.getElementById("minutes").value, 0);
  var s = parseInt(document.getElementById("seconds").value, 0);

  var now = new Date();
  var date = now.getTime();

  addDay = now.setDate(now.getDate() + d);
  addHour = now.setHours(now.getHours() + h);
  addMinute = now.setMinutes(now.getMinutes() + m);
  addSecond = now.setSeconds(now.getSeconds() + s);

  var then = new Date(addHour + addMinute + addSecond);

  if(d > 0 || h > 0 || m > 0 || s > 0){
    var final = then - date;
    var dd = Math.floor(final/ (1000 * 60 * 60 * 24));
    var hh = Math.floor((final / (1000 * 60 * 60)) % 24);
    var mm = Math.floor((final / 1000 / 60) % 60);
    var ss = Math.floor((final / 1000) % 60);

    document.getElementById("display").innerHTML = "Time Remaining: " + dd + "D     " + hh + "H " + mm + "M " + ss + "S";

    document.getElementById("message").innerHTML = then;

    if (final < 0) {
      clearInterval(countdownTimer);
      document.getElementById("message").innerHTML = "Expired";
    }
  }else{
    document.getElementById("display").innerHTML = " ";
    document.getElementById("message").innerHTML = "Countdown Not Started";
  }
}

HTML:

<div id="countdowntimer">
  <button id="Start" onclick="start();">Start Timer</button>

  D:<input type="text" id="days" value="0" /> 
  H:<input type="text" id="hours" value="0" /> 
  M:<input type="text" id="minutes" value="0" />
  S:<input type="text" id="seconds" value="0" /><br>

  <div id="display"></div>

  <div id="message"></div>
</div>

如果您的计时器不是基于日期而是基于给定的天数、小时数、分钟数和秒数,那么为什么要涉及日期呢?怎么样

function timer(){
    var d = parseInt(document.getElementById("days").value, 0);
    var h = parseInt(document.getElementById("hours").value, 0);
    var m = parseInt(document.getElementById("minutes").value, 0);
    var s = parseInt(document.getElementById("seconds").value, 0);

    var current = ((d * 86400) + (h * 3600) + (m * 60) + s);  //the current time left in seconds
    if (current > 0) {
        //take one second away, and rerender the seconds split into d, h, m, and s in the html, which you will reuse next time timer() runs
    } else {
        //expired
    }
}