当前位置:首页 > 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 的响应式特性和生命周期钩子,可以高效实现这一需求。 实现步骤 1. 数据准备 在 Vue 组件…

vue实现倒计时功能

vue实现倒计时功能

vue实现倒计时功能 在Vue中实现倒计时功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用setInterval和clearInterval 创建一个倒计时组件,利用setInter…

h5实现响应式代码

h5实现响应式代码

响应式设计基础 HTML5实现响应式设计主要通过媒体查询(Media Queries)、弹性布局(Flexbox)、网格布局(Grid)和视口设置(Viewport Meta Tag)等技术。核心目标…

php分页代码简单实现

php分页代码简单实现

基本分页实现 在PHP中实现分页功能通常需要结合MySQL的LIMIT子句。以下是一个基础实现示例: <?php // 数据库连接 $conn = mysqli_connect("localh…

js实现分页功能代码

js实现分页功能代码

分页功能实现方法 客户端分页(前端处理数据) 适用于数据量较小且已全部加载到前端的情况。 // 示例数据 const data = Array.from({length: 100}, (_, i)…

淘宝css代码制作

淘宝css代码制作

在淘宝店铺装修中,CSS代码用于自定义页面样式,提升视觉体验。以下是关键方法和注意事项: 自定义模块样式 通过淘宝旺铺的“自定义模块”功能,可以插入CSS代码。代码需包裹在<style>…