当前位置:首页 > JavaScript

js 实现倒计时

2026-04-03 18:06:40JavaScript

使用 setInterval 实现倒计时

通过 setInterval 定期更新倒计时显示,适用于简单的倒计时场景。

function countdown(seconds, elementId) {
  const element = document.getElementById(elementId);
  const timer = setInterval(() => {
    element.textContent = seconds;
    seconds--;
    if (seconds < 0) {
      clearInterval(timer);
      element.textContent = '时间到!';
    }
  }, 1000);
}

// 调用示例
countdown(10, 'countdown-display');

使用 requestAnimationFrame 实现高精度倒计时

适用于需要高精度计时的场景,如动画或游戏。

js 实现倒计时

function highPrecisionCountdown(duration, elementId) {
  const element = document.getElementById(elementId);
  const startTime = performance.now();

  function updateTimer(currentTime) {
    const elapsed = currentTime - startTime;
    const remaining = Math.max(0, duration - Math.floor(elapsed / 1000));
    element.textContent = remaining;

    if (remaining > 0) {
      requestAnimationFrame(updateTimer);
    } else {
      element.textContent = '时间到!';
    }
  }

  requestAnimationFrame(updateTimer);
}

// 调用示例
highPrecisionCountdown(10, 'countdown-display');

使用 Date 对象实现跨天倒计时

适用于需要显示天、小时、分钟和秒的长时间倒计时。

js 实现倒计时

function daysCountdown(endTime, elementId) {
  const element = document.getElementById(elementId);

  function update() {
    const now = new Date();
    const diff = endTime - now;

    if (diff <= 0) {
      element.textContent = '时间到!';
      return;
    }

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

    element.textContent = `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`;

    setTimeout(update, 1000);
  }

  update();
}

// 调用示例
const endDate = new Date();
endDate.setDate(endDate.getDate() + 2); // 2天后
daysCountdown(endDate, 'countdown-display');

使用 Web Worker 实现后台倒计时

适用于需要后台运行的倒计时,即使页面不活跃也能继续计时。

// main.js
function startWorkerCountdown(seconds, elementId) {
  const element = document.getElementById(elementId);
  const worker = new Worker('countdown-worker.js');

  worker.postMessage(seconds);

  worker.onmessage = function(e) {
    if (e.data === 'done') {
      element.textContent = '时间到!';
      worker.terminate();
    } else {
      element.textContent = e.data;
    }
  };
}

// countdown-worker.js
self.onmessage = function(e) {
  let seconds = e.data;

  const timer = setInterval(() => {
    self.postMessage(seconds);
    seconds--;

    if (seconds < 0) {
      clearInterval(timer);
      self.postMessage('done');
    }
  }, 1000);
};

使用 Promise 和 async/await 实现倒计时

适用于需要与其他异步操作配合的倒计时场景。

async function asyncCountdown(seconds, elementId) {
  const element = document.getElementById(elementId);

  for (let i = seconds; i >= 0; i--) {
    element.textContent = i;
    await new Promise(resolve => setTimeout(resolve, 1000));
  }

  element.textContent = '时间到!';
}

// 调用示例
asyncCountdown(10, 'countdown-display');

注意事项

  1. 性能考虑:setInterval 在页面不活跃时可能会延迟,requestAnimationFrame 或 Web Worker 更适合精确计时
  2. 内存泄漏:使用 setIntervalsetTimeout 时要记得清除定时器
  3. 跨标签页同步:如需多个标签页同步倒计时,可使用 BroadcastChannellocalStorage 事件
  4. 时区问题:使用 Date 对象时要注意客户端时区差异

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

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div cl…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整数…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…