当前位置:首页 > JavaScript

js实现倒计时

2026-04-03 17:50:22JavaScript

使用 setInterval 实现倒计时

通过 setInterval 定时器每秒更新剩余时间,并在倒计时结束时清除定时器。

js实现倒计时

function countdown(targetTime, callback) {
  const timer = setInterval(() => {
    const now = new Date().getTime();
    const distance = targetTime - now;

    if (distance <= 0) {
      clearInterval(timer);
      callback(0, 0, 0, 0);
      return;
    }

    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    callback(days, hours, minutes, seconds);
  }, 1000);
}

// 示例:倒计时到未来24小时
const targetTime = new Date().getTime() + 24 * 60 * 60 * 1000;
countdown(targetTime, (d, h, m, s) => {
  console.log(`${d}天 ${h}小时 ${m}分钟 ${s}秒`);
});

使用 requestAnimationFrame 实现高精度倒计时

适用于需要高精度渲染的场景(如动画),避免 setInterval 的时间漂移问题。

js实现倒计时

function animationCountdown(targetTime, callback) {
  let lastUpdate = 0;
  const update = (timestamp) => {
    if (timestamp - lastUpdate >= 1000) {
      const now = new Date().getTime();
      const distance = targetTime - now;

      if (distance <= 0) {
        callback(0, 0, 0, 0);
        return;
      }

      const days = Math.floor(distance / (1000 * 60 * 60 * 24));
      const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((distance % (1000 * 60)) / 1000);

      callback(days, hours, minutes, seconds);
      lastUpdate = timestamp;
    }
    requestAnimationFrame(update);
  };
  requestAnimationFrame(update);
}

使用 Web Worker 实现后台倒计时

避免主线程阻塞,适合长时间运行的倒计时场景。

// worker.js
self.onmessage = function(e) {
  const targetTime = e.data;
  setInterval(() => {
    const now = new Date().getTime();
    const distance = targetTime - now;
    postMessage(distance > 0 ? distance : 0);
  }, 1000);
};

// 主线程代码
const worker = new Worker('worker.js');
worker.postMessage(new Date().getTime() + 5000); // 5秒倒计时
worker.onmessage = (e) => {
  console.log(`剩余毫秒数: ${e.data}`);
};

格式化倒计时显示

将毫秒数转换为易读的字符串格式。

function formatCountdown(distance) {
  if (distance <= 0) return "00:00:00";
  const hours = Math.floor(distance / (1000 * 60 * 60)).toString().padStart(2, '0');
  const mins = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
  const secs = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0');
  return `${hours}:${mins}:${secs}`;
}

注意事项

  • 浏览器标签页休眠时,setInterval 可能被节流,建议用 Date 对象计算补偿时间。
  • 移动端页面隐藏时,requestAnimationFrame 会暂停,需监听 visibilitychange 事件。
  • 跨时区场景需统一使用 UTC 时间处理。

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

相关文章

js 实现vue模板

js 实现vue模板

实现 Vue 模板的 JavaScript 方法 通过原生 JavaScript 可以实现类似 Vue 的模板渲染功能,主要包括数据绑定、指令处理和模板解析。以下是核心实现思路: 数据绑定与响应式…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个回…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…