如何用原生js写一个能够加减时间的计时器?

案例:我想休息45分钟,希望到点了被网页弹窗提醒。也就是说,我能够输入起始时间,例如8:45:00,然后开始计时,它能够自动在9:30:00提示弹窗。

我认为难点在于,时钟是60分钟进一次位,和十进制不同。卡在这里不会写了。

目标:据说有把时间先转换为毫秒再转回去的方法,可以考虑用这种方法写。也希望能看到更简便的方法。需要具体代码,我非常笨。先感谢了。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let timer = null
    function timeFunc() {
          const date = new Date()
          const hours = date.getHours()
          const mins = date.getMinutes()
          const now = date.getTime()
          // 时间(毫秒)
          const start = new Date().setHours(12, 30, 0) // 开始时间 12:30:00
          const end = new Date().setHours(13, 0, 0) // 结束时间 13:00:00
          const ms = end - start // 休息时间
          /**
           * 现在到开始休息的剩余时间
           * 大于当前时间 时间未到,减去当前时间即可
           * 小于当前时间 时间已过,+24小时减去当前时间
           */
          let remTime = start > now ? (start - now) : (start + 86400000 - now)

          timer = setTimeout(timeFunc, remTime)
          // 开始休息时间
          if (hours === 12 && mins === 30) {
            console.log('开始休息!')
            setTimeout(() => {
              console.log('休息结束!')
            }, ms)
          }
    }
    timeFunc()
  </script>
</body>
</html>

img

搜索 “js date to unix timestamp”