当前位置:首页 > JavaScript

js实现倒计时

2026-01-12 12:58:29JavaScript

使用 setInterval 实现倒计时

通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。

function countdown(seconds, callback) {
  const timer = setInterval(() => {
    seconds--;
    callback(seconds);
    if (seconds <= 0) clearInterval(timer);
  }, 1000);
}

// 使用示例
countdown(10, (remaining) => {
  console.log(`剩余时间: ${remaining}秒`);
});

使用 requestAnimationFrame 实现高精度倒计时

通过递归调用 requestAnimationFrame 实现更高精度的倒计时,适合需要平滑动画的场景。

function preciseCountdown(endTime, updateCallback, finishCallback) {
  function update() {
    const now = Date.now();
    const remaining = Math.max(0, endTime - now);
    updateCallback(Math.ceil(remaining / 1000));

    if (remaining > 0) {
      requestAnimationFrame(update);
    } else {
      finishCallback?.();
    }
  }
  update();
}

// 使用示例
const targetTime = Date.now() + 10000; // 10秒后
preciseCountdown(
  targetTime,
  (sec) => console.log(`精确剩余: ${sec}秒`),
  () => console.log('倒计时结束')
);

带暂停/继续功能的倒计时类

封装一个完整的倒计时类,支持暂停、继续和重置功能。

class Countdown {
  constructor(duration, onUpdate, onComplete) {
    this.duration = duration;
    this.remaining = duration;
    this.onUpdate = onUpdate;
    this.onComplete = onComplete;
    this.timer = null;
    this.startTime = null;
  }

  start() {
    this.startTime = Date.now();
    this.timer = setInterval(() => {
      this.remaining = Math.max(0, this.duration - Math.floor((Date.now() - this.startTime) / 1000));
      this.onUpdate(this.remaining);
      if (this.remaining <= 0) {
        this.stop();
        this.onComplete?.();
      }
    }, 1000);
  }

  pause() {
    clearInterval(this.timer);
    this.duration = this.remaining;
  }

  stop() {
    clearInterval(this.timer);
    this.remaining = this.duration;
  }
}

// 使用示例
const cd = new Countdown(
  30,
  (sec) => console.log(`高级剩余: ${sec}秒`),
  () => console.log('高级倒计时结束')
);
cd.start();

格式化显示的倒计时

添加时间格式化功能,将秒数转换为 HH:MM:SS 格式。

function formatTime(seconds) {
  const hours = Math.floor(seconds / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;

  return [
    hours.toString().padStart(2, '0'),
    mins.toString().padStart(2, '0'),
    secs.toString().padStart(2, '0')
  ].join(':');
}

// 结合到之前的示例中
countdown(3665, (remaining) => {
  console.log(`格式化显示: ${formatTime(remaining)}`);
});

注意事项

  1. 浏览器标签页处于非激活状态时,setInterval 可能会被节流,导致计时不准
  2. 使用 requestAnimationFrame 可以改善精度但更耗性能
  3. 清除定时器时务必使用 clearIntervalcancelAnimationFrame
  4. 长时间倒计时应考虑使用服务器时间同步

js实现倒计时

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

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现

js实现

JavaScript 实现方法 JavaScript 是一种广泛使用的编程语言,适用于网页开发、服务器端编程以及移动应用开发。以下是几种常见的 JavaScript 实现方法: 网页交互功能 使用…

js实现轮播

js实现轮播

实现基础轮播效果 使用HTML结构创建轮播容器和图片元素: <div class="carousel"> <div class="carousel-inner">…

js实现分页

js实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Promis…