当前位置:首页 > 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,复杂控制需求可选择类封装方案。

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

相关文章

vue怎么实现文本代码实现

vue怎么实现文本代码实现

Vue 实现文本代码展示的方法 在 Vue 中展示代码文本通常需要结合语法高亮和格式化的功能,以下是几种常见的实现方式: 使用 <pre> 和 <code> 标签 通过 HT…

vue抽奖代码实现

vue抽奖代码实现

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

vue 实现代码

vue 实现代码

Vue 是一个流行的前端框架,用于构建用户界面。以下是一个简单的 Vue 实现代码示例,展示如何创建一个基本的 Vue 应用。 安装 Vue 通过 CDN 引入 Vue: <script s…

vue分页代码实现

vue分页代码实现

Vue 分页代码实现 在 Vue 中实现分页功能通常需要结合后端 API 返回的数据和前端的分页组件。以下是一个完整的实现示例,包括分页组件的封装和与后端数据的交互。 分页组件封装 创建一个…

vue 实现点击复制 代码

vue 实现点击复制 代码

vue 实现点击复制功能 使用Vue实现点击复制功能可以通过原生JavaScript的document.execCommand或现代的Clipboard API。以下是几种常见实现方式: 使用doc…

vue倒计时实现

vue倒计时实现

Vue 倒计时实现方法 使用 setInterval 基础实现 在 Vue 组件中,通过 data 定义倒计时初始值,使用 setInterval 实现倒计时逻辑,并在组件销毁时清除定时器。 <…