当前位置:首页 > JavaScript

用js实现一个倒计时器

2026-03-02 03:37:45JavaScript

实现倒计时器的基本方法

使用JavaScript实现倒计时器可以通过setIntervalrequestAnimationFrame结合时间差计算来完成。以下是两种常见的实现方式。

用js实现一个倒计时器

基于setInterval的倒计时器

创建一个简单的倒计时器,显示剩余时间并支持暂停和重置功能。

用js实现一个倒计时器

class CountdownTimer {
  constructor(duration, displayElement) {
    this.duration = duration; // 总时长(秒)
    this.displayElement = displayElement;
    this.remainingTime = duration;
    this.timerId = null;
  }

  start() {
    if (this.timerId) return;
    this.timerId = setInterval(() => {
      this.remainingTime--;
      this.updateDisplay();
      if (this.remainingTime <= 0) {
        this.stop();
      }
    }, 1000);
  }

  stop() {
    clearInterval(this.timerId);
    this.timerId = null;
  }

  reset() {
    this.stop();
    this.remainingTime = this.duration;
    this.updateDisplay();
  }

  updateDisplay() {
    const minutes = Math.floor(this.remainingTime / 60);
    const seconds = this.remainingTime % 60;
    this.displayElement.textContent = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  }
}

// 使用示例
const display = document.getElementById('countdown-display');
const timer = new CountdownTimer(300, display); // 5分钟倒计时
document.getElementById('start-btn').addEventListener('click', () => timer.start());
document.getElementById('stop-btn').addEventListener('click', () => timer.stop());
document.getElementById('reset-btn').addEventListener('click', () => timer.reset());

基于requestAnimationFrame的高精度倒计时器

如果需要更高精度或更流畅的动画效果,可以使用requestAnimationFrame

class HighPrecisionCountdown {
  constructor(duration, displayElement) {
    this.duration = duration * 1000; // 转换为毫秒
    this.displayElement = displayElement;
    this.startTime = null;
    this.remainingTime = this.duration;
    this.animationId = null;
  }

  start() {
    if (this.animationId) return;
    this.startTime = performance.now();
    this.animationId = requestAnimationFrame(this.update.bind(this));
  }

  update(timestamp) {
    const elapsed = timestamp - this.startTime;
    this.remainingTime = Math.max(0, this.duration - elapsed);
    this.render();
    if (this.remainingTime > 0) {
      this.animationId = requestAnimationFrame(this.update.bind(this));
    }
  }

  stop() {
    cancelAnimationFrame(this.animationId);
    this.animationId = null;
  }

  reset() {
    this.stop();
    this.remainingTime = this.duration;
    this.render();
  }

  render() {
    const totalSeconds = Math.ceil(this.remainingTime / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    this.displayElement.textContent = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  }
}

// 使用示例
const display = document.getElementById('high-precision-countdown');
const highPrecisionTimer = new HighPrecisionCountdown(300, display);
document.getElementById('start-btn').addEventListener('click', () => highPrecisionTimer.start());
document.getElementById('stop-btn').addEventListener('click', () => highPrecisionTimer.stop());
document.getElementById('reset-btn').addEventListener('click', () => highPrecisionTimer.reset());

注意事项

  • setInterval可能存在时间漂移问题,长时间运行后可能不准确。
  • requestAnimationFrame更适合需要平滑动画的场景,但会消耗更多资源。
  • 页面不可见时(如切换到其他标签页),requestAnimationFrame会暂停执行,而setInterval可能继续运行但会被浏览器限制。

标签: 计时器js
分享给朋友:

相关文章

js轮播图实现原理

js轮播图实现原理

轮播图的基本原理 轮播图通过动态切换显示的内容(图片、文本等)实现视觉上的滑动效果。核心原理是利用CSS和JavaScript控制元素的显示与隐藏,或通过变换位置实现滑动动画。 实现方法一:CSS…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…

实现继承js

实现继承js

实现继承的方式 在JavaScript中,实现继承可以通过多种方式完成,每种方式都有其优缺点。以下是几种常见的实现继承的方法: 原型链继承 原型链继承是最基本的继承方式,通过将子类的原型指向父类的实…