当前位置:首页 > JavaScript

js代码实现倒计时

2026-01-30 20:19:51JavaScript

使用 setInterval 实现倒计时

通过 setInterval 定期更新剩余时间,适用于简单的倒计时需求。

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

// 示例:10秒倒计时
countdown(10, () => console.log('倒计时结束'));

使用 requestAnimationFrame 实现高精度倒计时

适用于需要高精度或动画效果的场景,避免 setInterval 的时间漂移问题。

js代码实现倒计时

function highPrecisionCountdown(duration, callback) {
  const startTime = performance.now();

  function update() {
    const elapsed = performance.now() - startTime;
    const remaining = Math.max(0, duration - Math.floor(elapsed / 1000));

    console.log(remaining);
    if (remaining > 0) {
      requestAnimationFrame(update);
    } else {
      callback();
    }
  }

  requestAnimationFrame(update);
}

// 示例:5秒高精度倒计时
highPrecisionCountdown(5, () => console.log('高精度倒计时结束'));

动态显示到目标时间的倒计时

计算当前时间到目标时间的差值,适合显示距离未来某个时间点的倒计时。

js代码实现倒计时

function targetCountdown(targetDate, updateCallback, endCallback) {
  function tick() {
    const now = new Date();
    const diff = targetDate - now;

    if (diff <= 0) {
      endCallback();
      return;
    }

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

    updateCallback({ days, hours, mins, secs });
    setTimeout(tick, 1000);
  }

  tick();
}

// 示例:显示到明天此时的倒计时
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

targetCountdown(
  tomorrow,
  ({ days, hours, mins, secs }) => {
    console.log(`${days}天 ${hours}时 ${mins}分 ${secs}秒`);
  },
  () => console.log('目标时间已到')
);

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

通过封装计时器逻辑实现可控制的倒计时。

class PausableCountdown {
  constructor(duration, callback) {
    this.duration = duration;
    this.callback = callback;
    this.remaining = duration;
    this.timer = null;
    this.startTime = null;
  }

  start() {
    this.startTime = Date.now();
    this.timer = setInterval(() => {
      this.remaining--;
      console.log(this.remaining);
      if (this.remaining <= 0) {
        this.stop();
        this.callback();
      }
    }, 1000);
  }

  pause() {
    clearInterval(this.timer);
    this.timer = null;
    this.remaining -= Math.floor((Date.now() - this.startTime) / 1000);
  }

  stop() {
    clearInterval(this.timer);
    this.timer = null;
  }
}

// 使用示例
const countdown = new PausableCountdown(10, () => console.log('完成'));
countdown.start();

// 暂停示例(通常在事件中调用)
// setTimeout(() => countdown.pause(), 3000);

使用 Web Worker 实现后台倒计时

避免主线程阻塞,适合需要长时间运行且精确的倒计时。

// worker.js
let timer;
self.onmessage = function(e) {
  if (e.data.command === 'start') {
    let seconds = e.data.seconds;
    timer = setInterval(() => {
      seconds--;
      self.postMessage(seconds);
      if (seconds <= 0) clearInterval(timer);
    }, 1000);
  } else if (e.data.command === 'stop') {
    clearInterval(timer);
  }
};

// 主线程代码
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
  console.log(e.data);
  if (e.data <= 0) console.log('Worker倒计时结束');
};

// 启动15秒倒计时
worker.postMessage({ command: 'start', seconds: 15 });

// 停止示例
// worker.postMessage({ command: 'stop' });

每种方法适用于不同场景,可根据需求选择实现方式。简单场景推荐 setInterval,需要高精度时使用 requestAnimationFrame,复杂控制需求可选择类封装方案。

标签: 倒计时代码
分享给朋友:

相关文章

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

uniapp倒计时组件

uniapp倒计时组件

uniapp倒计时组件实现方法 使用内置组件实现 uniapp提供了<countdown>组件用于倒计时功能,支持自定义格式和样式。示例代码如下: <countdown :t…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <…

vue实现代码

vue实现代码

以下是Vue实现常见功能的代码示例,涵盖基础语法、组件通信、状态管理等核心内容: 基础模板语法 <template> <div> <h1>{{ mes…

vue抽奖代码实现

vue抽奖代码实现

Vue 抽奖代码实现 基础抽奖组件结构 使用 Vue 3 的 Composition API 实现抽奖功能,核心包括转盘动画、奖品列表和抽奖逻辑。以下为组件基础结构: <templat…

vue简单代码实现

vue简单代码实现

以下是一个基于 Vue 3 的简单代码实现示例,包含基础功能演示: 基础模板结构 <!DOCTYPE html> <html lang="en"> <head>…