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

版权声明:一只会飞的狼 https://blog.csdn.net/sinat_40697723/article/details/87708598

可以在点击函数里面先设置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>

猜你喜欢

转载自blog.csdn.net/sinat_40697723/article/details/87708598