我是Java语言的新手,现在正在尝试倒数计时器。每次完成倒数计时时,页面弹出警报框都会显示:倒数结束。但是每次我单击“确定”时,警报框都不会关闭。我认为它与windows.onload函数有关,但是我不知道如何解决它。



function startTimer(duration, display) {
  var timer = duration,
    minutes,
    seconds;

  setInterval(function() {
    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) {
      timer = 0;
      alert('countdown finished');
      document.getElementById('demo').innerHTML = 'EXPIRED';
    }
  }, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 0.1,
    //display = document.querySelector('#time');
    display = document.getElementById('demo');
  startTimer(fiveMinutes, display);
};

<h1>conutdown</h1>
<p id="demo"></p>
<!-- <div>Registration closes in <span id="time">05:00</span> minutes!</div> -->

最佳答案

您必须使用clearInterval()清除间隔



<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>countdown</title>
  </head>

  <body>
    <h1>conutdown</h1>
    <p id="demo"></p>
    <!-- <div>Registration closes in <span id="time">05:00</span> minutes!</div> -->

<script>

function startTimer(duration, display) {
  var timer = duration,
    minutes,
    seconds;

var intrvl = setInterval(function() {
    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) {
      timer = 0;
      alert('countdown finished');
      document.getElementById('demo').innerHTML = 'EXPIRED';
      clearInterval(intrvl); // Clears interval
    }
  }, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 0.1,
    //display = document.querySelector('#time');
    display = document.getElementById('demo');
  startTimer(fiveMinutes, display);
};

</script>
</body>
</html>

关于javascript - 警报框javascript无法关闭,因为window.onload,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58317347/

10-09 19:20