当前位置:首页 > JavaScript

js实现倒计时

2026-01-12 12:58:29JavaScript

使用 setInterval 实现倒计时

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

js实现倒计时

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

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

使用 requestAnimationFrame 实现高精度倒计时

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

js实现倒计时

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实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…