js實現指定時間倒數計時

_噠噠噠就是大發表於2020-09-27
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>js實現指定時間倒數計時</title>
  </head>

  <body>
    <div id="leftTime"></div>
    <script>
      // 預計時間
      var expectTime = "2020-9-27 16:19:00"
      var nowTime = +new Date() //當前時間總的毫秒數
      var inputTime = +new Date(expectTime) //使用者輸入時間總的毫秒數
      var times = (inputTime - nowTime) / 1000 //times是剩餘時間總的毫秒數

      var timer = setInterval(function () {
        times--
        var d = (d = parseInt(times / 60 / 60 / 24))
        d = d < 10 ? "0" + d : d
        var h = parseInt((times / 60 / 60) % 24)
        h = h < 10 ? "0" + h : h
        var m = parseInt((times / 60) % 60)
        m = m < 10 ? "0" + m : m
        var s = parseInt(times % 60)

        if (s > 0) {
          s = s < 10 ? "0" + s : s
          var countdown = d + "天" + h + "時" + m + "分" + s + "秒"
          document.getElementById("leftTime").innerHTML = countdown
        }
        if (s == 0) {
          console.log("結束了0s")
          var countdown = "00天00時00分00秒"
          document.getElementById("leftTime").innerHTML = countdown
          clearInterval(timer)
        }
        if (s < 0) {
          var countdown = "00天00時00分00秒"
          document.getElementById("leftTime").innerHTML = countdown
          clearInterval(timer)
        }
      }, 1000)
    </script>
  </body>
</html>

相關文章