js解决高频率点击带来的定时器问题

可以在点击函数里面先设置clearInterval(timer),然后再设置定时器timer = setInterval(...........);

下面的例子就成功的解决了这个问题:

//一个计时器

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
    section {
      width: 400px;
      height: 200px;
      margin: 50px auto;
    }

    .text {
      width: 300px;
      height: 50px;
      margin: 20px auto;
      text-align: center;
      line-height: 50px;
      font-size: 16px;
      color: green;
      border: 1px solid green;
    }

    .btn {
      width: 200px;
      height: 30px;
      margin: 20px auto;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }

    button {
      cursor: pointer;
    }
  </style>
</head>
<body>
	<section>
	  <div class="text" id="word"></div>
	  <div class="btn">
	    <button id="btn-start">开始</button>
	    <button id="btn-stop">暂停</button>
	    <button id="btn-reset">重置</button>
	  </div>
	</section>
  <script type="text/javascript">
    let timer = null;
    let h = 0, m = 0, s = 0, ms = 0;
    let str = `00时00分00秒000毫秒`;
    let word = getId('word');
    word.innerText = str;
    function getId(id) {
      return typeof(id) === 'string' ? document.getElementById(id) : id;
    }
    
    function timeAdd() {
      ms += 50;
      if (ms === 1000) {
        s += 1;
        ms = 0;
      };
      if (s === 60) {
        m += 1;
        s = 0;
      };
      if (m === 60) {
        h += 1;
        m = 0;
      };
      str = `${one(h)}时${one(m)}分${one(s)}秒${two(ms)}毫秒`;
      word.innerText = str;
    }

    function start() {
      clearInterval(timer);
      timer = setInterval(timeAdd, 50);
    }
    function stop() {
      clearInterval(timer);
    }
    function reset() {
    	clearInterval(timer);
      str = `00时00分00秒000毫秒`;
      word.innerText = str;
    }
    getId('btn-start').onclick = start;
    getId('btn-stop').onclick = stop;
    getId('btn-reset').onclick = reset;
    function one(n) {
      if (n < 10) {
        return '0' + n;
      } else {
        return '' + n;
      }
    }
    function two(m) {
      if (m < 100 && m >= 10) {
        return '0' + m;
      } else if (m < 10) {
        return '00' + m;
      } else {
        return m;
      }
    }
  </script>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值