代码之家  ›  专栏  ›  技术社区  ›  DolDurma

带soporting cancel和restart的JavaScript倒计时

  •  -1
  • DolDurma  · 技术社区  · 3 年前

    javascript 我想做一个简单的 CountDownTimer setInterval 这只是回报 4 控制台中的数字,我无法修复。没有假设这个问题 clearInterval 不工作,我想支持取消和重新启动这一次

    <script type="text/javascript">
        var fiveMinutes = 5, display = document.querySelector('#time');
        let myTimer = function (){
            let timer = fiveMinutes, minutes, seconds;
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
            display.textContent = minutes + ":" + seconds;
            if (--timer < 0) {
                $('#resend').show();
                $('#time').hide();
                clearInterval(this);
            }
            console.log(timer);
        };
        $('#startTimer').on('click', function(){
            $('#resend').hide();
            $('#time').show();
            setInterval(myTimer , 1000);
        });
    </script>
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Guerric P    3 年前

    你的代码固定在下面。主要问题是 fiveMinutes closure . 同样,它也没有乘以60在几秒钟内被转换。

    var display = document.querySelector('#time');
    let myTimer = function (timer) {
      return function () {
        let minutes, seconds;
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (--timer < 0) {
          $('#resend').show();
          $('#time').hide();
          clearInterval(this);
        }
        console.log(timer);
      }
    
    };
    $('#startTimer').on('click', function () {
      $('#resend').hide();
      $('#time').show();
      setInterval(myTimer(5 * 60), 1000);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="time"></div>
    <button id="startTimer">Start</button>