JavaScript 倒数计时器,按下按键可重置计时器 [英] JavaScript countdown timer with on key press to reset the timer

查看:71
本文介绍了JavaScript 倒数计时器,按下按键可重置计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚当我按下一个键时它是如何从 30 倒数到 0 的,如果我再次按下那个键,它会做同样的事情,从 30 到 0(重置).

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).

有什么办法可以用 JavaScript 来完成,并且在 HTML 中只显示从 30 到 0 的数字而没有其他文本?

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?

我尝试过使用其他示例,但是我认为我必须将脚本放在错误的位置.有人能给我一个不仅是 JS 的例子,还有 HTML 标记应该是什么样子的例子吗?将不胜感激.

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>

推荐答案

这是使用 setInterval,至少在 n 毫秒后调用其参数函数(1000 ms = 1s)过去了.

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.keyCode === 88) { // x key
    clearInterval(interval);
    count = 30;
    interval = setInterval(() => {
      timer.innerText = count--;

      if (count < 0) {
        clearInterval(interval);
      }
    }, 1000);
  }
});

<div id="timer">press "x" key</div>

这里的问题是提供给 setTimeout 的 1000 毫秒是调用之间的最小延迟.超过 1000 ms 的延迟会累积并导致漂移.

The problem here is that the 1000 ms provided to setTimeout is a minimum delay between calls. Delays beyond 1000 ms will accumulate and cause drift.

考虑使用 日期/时间库 如果精度很重要.requestAnimationFrame 也可以确保不会错过任何渲染,并且倒计时的更改(例如重置事件)可以快速反映到用户界面.

Consider using a date/time library if precision is important. requestAnimationFrame can also be handy to ensure that no renders are missed and that changes to the countdown (such as a reset event) reflect to the user interface quickly.

为了保持作用域干净,我们可以使用闭包来初始化和运行计数器循环.这个倒计时初始化器可以返回一个函数来停止计数器,由事件处理程序调用.

To keep scope clean, we can use a closure to initialize and run the counter loop. This countdown initializer can return a function to stop the counter, invocable by an event handler.

const runCountdown = (counter, el) => {
  let start = Date.now() / 1000;
  let running = true;

  (function tick() {
    const elapsed = Date.now() / 1000 - start;
    el.innerText = counter - Math.floor(elapsed);

    if (running && elapsed < counter) {
      requestAnimationFrame(tick);
    }
  })();
  
  return () => (running = false);
};

let stop; 
document.addEventListener("keydown", e => {
  if (e.keyCode === 88) { // x key
    stop && stop();
    stop = runCountdown(30, document.querySelector("#count"));
  }
});

<p>Press the "x" key to start or restart the countdown.</p>
<div id="count"></div>

这篇关于JavaScript 倒数计时器,按下按键可重置计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆