📌  相关文章
📜  JavaScript程序创建倒数计时器(1)

📅  最后修改于: 2023-12-03 15:16:18.410000             🧑  作者: Mango

JavaScript程序创建倒数计时器

简介

倒数计时器可以帮助用户倒计时剩余时间,同时提醒用户在规定时间内完成任务。本文将介绍如何使用 JavaScript 创建一个倒数计时器。

实现步骤
  1. 创建一个 HTML 文件,包含倒数计时器所需的标签元素。示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>倒数计时器</title>
</head>
<body>
  <div id="countdown">
    <h1>倒数计时器</h1>
    <p>剩余时间:<span id="timer">00:00:00</span></p>
    <button id="startBtn">开始计时</button>
    <button id="pauseBtn">暂停计时</button>
    <button id="resetBtn">重置计时</button>
  </div>
</body>
</html>
  1. 编写 JavaScript 代码,处理倒计时逻辑。示例代码如下:
const Countdown = function(duration, display) {
  this.duration = duration;
  this.display = display;
  this.timerRunning = false;
  this.elapsedTime = 0;
  this.interval = null;
};

Countdown.prototype.start = function() {
  if (!this.timerRunning) {
    this.timerRunning = true;
    const start = Date.now();
    this.interval = setInterval(() => {
      this.elapsedTime = Date.now() - start;
      this.updateTime();
    }, 10);
  }
};

Countdown.prototype.pause = function() {
  clearInterval(this.interval);
  this.timerRunning = false;
};

Countdown.prototype.reset = function() {
  this.elapsedTime = 0;
  this.updateTime();
};

Countdown.prototype.updateTime = function() {
  let timeRemaining = this.duration - this.elapsedTime;
  if (timeRemaining < 0) {
    timeRemaining = 0;
    this.pause();
  }
  const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
  this.display.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

const countdown = new Countdown(10 * 60 * 1000, document.getElementById('timer'));

document.getElementById('startBtn').addEventListener('click', () => {
  countdown.start();
});

document.getElementById('pauseBtn').addEventListener('click', () => {
  countdown.pause();
});

document.getElementById('resetBtn').addEventListener('click', () => {
  countdown.reset();
});
  1. 运行 HTML 文件,测试倒计时器功能。在浏览器中打开 HTML 文件,点击“开始计时”按钮即可开始倒计时。
代码解析
  1. Countdown 构造函数接受两个参数,duration 表示倒计时总时间(单位为毫秒),display 表示显示倒计时剩余时间的元素。构造函数中还定义了四个字段,分别表示倒计时是否正在运行、已经流逝的时间、计时器间隔 ID 和当前实例的 this 对象。

  2. 构造函数定义了三个方法,分别对应开始计时、暂停计时和重置计时的操作。开始计时方法中使用了 setInterval 函数,每隔 10 毫秒更新一次倒计时显示的时间。

  3. updateTime 方法用于更新倒计时显示的时间。该方法首先计算离倒计时结束时间还剩下多少时间,如果剩余时间小于 0,则将剩余时间设为 0,并暂停计时器。接着,方法使用 Math.floor 函数计算出剩余时间的小时、分钟和秒数,并使用 padStart 函数在数字前面增加前导零,保证倒计时格式的一致性。最后,方法将更新后的倒计时值设置为 display 元素的文本内容。

  4. 创建 Countdown 类的实例,传入倒计时总时间和显示倒计时的元素。同时,获取“开始计时”、“暂停计时”和“重置计时”三个按钮,为这些按钮设置点击事件监听器,对应调用 Countdown 实例的 start、pause 和 reset 方法。

总结

我们可以使用 JavaScript 创建一个倒数计时器,帮助用户倒计时剩余时间,并提醒用户在规定时间内完成任务。实现步骤包括在 HTML 文件中添加必要的标签元素,编写处理倒计时逻辑的 JavaScript 代码。本文介绍的 Countdown 类实现了开始计时、暂停计时和重置计时的功能,展示了如何计算剩余时间和更新倒计时显示的内容。