JS实现简易计时器

发布时间:2020-02-28 00:20:57 作者:Cherish纯紫
来源:网络 阅读:262
<!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" />
    <style>
      .container {
        width: 300px;
        height: 100px;
        background-color: #eee;
        padding: 20px 10px;
        margin: 100px auto;
      }
      .box {
        width: 100px;
        height: 30px;
        margin: 30px auto;
      }
      .box span {
        color: red;
        font-size: 20px;
        display: inline-block;
        padding: 0 5px;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <input type="number" id="time" />
      <button id="btn1">计时开始</button>
      <button id="btn2">暂停</button>
      <button id="btn3">结束</button>
      <div class="box">倒计时<span></span>秒</div>
    </div>
  </body>

  <script>
    var time = document.querySelector('#time')
    var btn1 = document.querySelector('#btn1')
    var btn2 = document.querySelector('#btn2')
    var btn3 = document.querySelector('#btn3')
    var span = document.querySelector('.box').children[0]
    // 计时
    btn1.addEventListener('click', function() {
      var val = time.value
      time.value = ''
      if (!val) {
        alert('请输如大于0的时间,单位:秒')
      } else {
        var timeId = funTime(val)
      }

      // 暂停
      btn2.addEventListener('click', function() {
        var txt = btn2.innerHTML
        if (span.innerHTML) {
          if (txt == '暂停') {
            clearInterval(timeId)
            btn2.innerHTML = '开始'
          } else {
            timeId = funTime(span.innerHTML)
            btn2.innerHTML = '暂停'
          }
        }
      })

      // 结束
      btn3.addEventListener('click', function() {
        if (timeId) {
          clearInterval(timeId)
          span.innerHTML = ''
        }
      })

      // 计时器函数
      function funTime(val) {
        span.innerHTML = val
        var timer = setInterval(() => {
          if (val === 0) {
            clearInterval(timeId)
            span.innerHTML = ''
            alert('时间到!')
          } else {
            val--
            span.innerHTML = val
          }
        }, 1000)
        return timer
      }
    })
  </script>
</html>
推荐阅读:
  1. JS如何实现简易留言板
  2. JS实现简易留言板特效

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js 计时器 j

上一篇:mongodb之Linux下安装

下一篇:拨开市场迷雾,SD-WAN市场的守与攻

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》