当前位置:首页 > 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 实现高精度倒计时

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

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 对象实现跨天倒计时

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

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 实现倒计时

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

js 实现倒计时

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
分享给朋友:

相关文章

vue实现倒计时抢券

vue实现倒计时抢券

实现思路 通过 Vue 的响应式数据绑定和定时器功能,结合计算属性动态展示倒计时剩余时间,并在倒计时结束后触发抢券逻辑。 核心代码实现 <template> <div>…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…

js画图实现

js画图实现

使用Canvas API绘制图形 Canvas是HTML5提供的绘图API,通过JavaScript操作Canvas元素可以绘制各种图形。以下是一个简单的示例: <canvas id="myC…

js节流实现

js节流实现

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

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 const…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…