jQuery计数器启动/停止/重置没有正确停止

问题描述 投票:0回答:1

我正在尝试使用setInterval()构建一个jQuery计数器,想法是计数器应该在按下按钮后开始计数,然后如果按下另一个按钮则应该停止+重置为零,这个过程应该是可重复的,但是我的JS似乎没有停止计时器,即使我的变量设置显示false。计时器应该只计算它是否为true

$('.start').click(function() {
      timer(true)
    })

    $('.stop').click(function() {
      timer(false)
    })

    let timerShouldCount = false

    function timer(timerStatus) {
      timerShouldCount = timerStatus
      if (timerShouldCount == true ) {
        setInterval(function(){
          console.log('counting');
        }, 1000);
      }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="start" type="button">Start</button>
        <button class="stop" type="button">Stop</button>

UPDATE

$('.js_ask-later').click(function() {
        timer(true)
      })
      $('.js_close-modal').click(function() {
        timer(false)
      })

      let registerTimer
      let timerShouldCount = false

      function timer(timerStatus) {
        timerShouldCount = timerStatus
        if (timerShouldCount == true) {
          $('#login-modal').on('hidden.bs.modal', function (e) {
            registerTimer = setInterval(function(){
              $('#login-modal').modal('show')
            }, 5000)
          })
        } else {
          clearInterval(registerTimer)
        }
      }
javascript jquery html
1个回答
2
投票

你没有在任何时候清除间隔。为此,您需要引用创建的间隔。

let my_int;

function timer(timerStatus) {
    timerShouldCount = timerStatus
    if (timerShouldCount == true ) {
        my_int = setInterval(function(){
            console.log('counting');
        }, 1000);
    } else
        clearInterval(my_int);
}

[编辑]

继下面的评论之后,很明显你实际上没有计时器,只是一个间隔。我们需要一个定时器的var。

let my_int, timer = 0;

function timer(timerStatus) {
    timerShouldCount = timerStatus
    if (timerShouldCount == true ) {
        my_int = setInterval(function(){
            timer++; //<-- increment
            console.log('counting');
        }, 1000);
    } else {
        clearInterval(my_int);
        timer = 0; //<-- reset to 0
    }
}

您使用该计时器所做的事情,即您在DOM中显示它的位置取决于您,但您现在至少可以看到我们如何递增它并将其重置为0。

© www.soinside.com 2019 - 2024. All rights reserved.