Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

setinterval - JavaScript countdown timer with on key press to reset the timer

I'm trying to work out how when I press a key it counts down from 30 to 0, and if i press that key again it does the same thing, counts from 30 to 0 (resets).

Is there some way this is can be done with JavaScript and in the HTML only have it displaying the numbers counting from 30 to 0 with no other text?

I have tried using other examples however I think i must be putting the script into the wrong place. Is someone able to give me an example not just of the JS but also what the HTML markup should look like? Would be much appreciated.

The example I have been trying to modify and play with is:

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <h2>JavaScript in Body</h2>
  <p id="demo"></p>

  <script>
    $(function() {

      var perc = 50 // User will be logged out after (minutes)
      var count = perc * 60;

      // RESET TIMER

      $(document).keypress(function() {
        var count = perc * 60; // PROBLEM
        alert('keypress works');
      });

      //COUNTDOWN

      var counter = setInterval(timer, 1000);

      function timer() {
        count = count - 1;
        if (count == -1) {
          // LOGOUT //
          return;
        }

        var seconds = count % 60;
        var minutes = Math.floor(count / 60);

        seconds %= 60;
        minutes %= 60;

        document.getElementById("seconds").innerHTML = seconds;
        document.getElementById("minutes").innerHTML = minutes;
        document.getElementById("start_time").innerHTML = inactive;
      };
    });
  </script>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's the naive approach for a one-second countdown using setInterval, which calls its parameter function after at least n milliseconds (1000 ms = 1s) elapses.

/* an inaccurate counter */
let count;
let interval;
const timer = document.querySelector("#timer");

document.addEventListener("keydown", e => {
  if (e.code === "KeyX") {
    clearInterval(interval);
    count = 30;
    interval = setInterval(() => {
      timer.innerText = count--;

      if (count < 0) {
        clearInterval(interval);
      }
    }, 1000);
  }
});
<div id="timer">press "x" key</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...