当前位置:首页 > JavaScript

js代码实现倒计时

2026-03-01 11:24:37JavaScript

使用 setInterval 实现倒计时

通过 setInterval 定时器每秒更新显示剩余时间,适用于简单的倒计时场景。

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

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

使用 setTimeout 递归实现

递归调用 setTimeout 实现更精确的倒计时控制,避免 setInterval 的误差累积问题。

function recursiveCountdown(seconds, callback) {
  console.log(seconds);
  if (seconds > 0) {
    setTimeout(() => recursiveCountdown(seconds - 1, callback), 1000);
  } else {
    callback?.();
  }
}

// 使用示例
recursiveCountdown(5, () => console.log('时间到'));

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

通过封装倒计时逻辑实现可控制的倒计时器,支持暂停和继续功能。

class Countdown {
  constructor(seconds, callback) {
    this.seconds = seconds;
    this.callback = callback;
    this.timer = null;
  }

  start() {
    this.timer = setInterval(() => {
      this.seconds--;
      console.log(this.seconds);
      if (this.seconds <= 0) {
        this.stop();
        this.callback?.();
      }
    }, 1000);
  }

  pause() {
    clearInterval(this.timer);
  }

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

// 使用示例
const cd = new Countdown(3, () => console.log('完成'));
cd.start();
// cd.pause(); // 暂停
// cd.start(); // 继续

精确到毫秒的倒计时

使用 performance.now() 实现高精度倒计时,适用于需要精确计时的场景。

function preciseCountdown(duration, updateCallback, endCallback) {
  const startTime = performance.now();
  let requestId;

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

    if (remaining > 0) {
      requestId = requestAnimationFrame(update);
    } else {
      endCallback?.();
    }
  }

  requestId = requestAnimationFrame(update);

  return {
    stop: () => cancelAnimationFrame(requestId)
  };
}

// 使用示例
const counter = preciseCountdown(
  5000,
  (ms) => console.log((ms/1000).toFixed(2)),
  () => console.log('精确倒计时结束')
);
// counter.stop(); // 可随时停止

页面显示的倒计时组件

实现一个在网页上显示的完整倒计时组件,包含 HTML 结构和样式控制。

<div id="countdown-display">00:00:00</div>
<button id="start-btn">开始</button>
<button id="pause-btn">暂停</button>

<script>
  class DisplayCountdown {
    constructor(displayElement, initialSeconds) {
      this.display = displayElement;
      this.seconds = initialSeconds;
      this.timer = null;
      this.updateDisplay();
    }

    start() {
      if (!this.timer && this.seconds > 0) {
        this.timer = setInterval(() => {
          this.seconds--;
          this.updateDisplay();
          if (this.seconds <= 0) this.stop();
        }, 1000);
      }
    }

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

    stop() {
      this.pause();
      this.seconds = 0;
      this.updateDisplay();
    }

    updateDisplay() {
      const hours = Math.floor(this.seconds / 3600);
      const mins = Math.floor((this.seconds % 3600) / 60);
      const secs = this.seconds % 60;
      this.display.textContent = 
        `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
  }

  // 使用示例
  const display = new DisplayCountdown(document.getElementById('countdown-display'), 30);
  document.getElementById('start-btn').addEventListener('click', () => display.start());
  document.getElementById('pause-btn').addEventListener('click', () => display.pause());
</script>

时区敏感的倒计时

处理跨时区倒计时需求,确保在不同时区显示正确的剩余时间。

function timezoneCountdown(targetDate, updateCallback) {
  function update() {
    const now = new Date();
    const diff = targetDate - now;
    if (diff <= 0) {
      updateCallback?.(0);
      return;
    }

    const seconds = Math.floor(diff / 1000);
    updateCallback?.(seconds);
    setTimeout(update, 1000);
  }

  update();
}

// 使用示例:计算到2023年12月31日的倒计时
const newYear = new Date('2023-12-31T23:59:59Z');
timezoneCountdown(newYear, (sec) => {
  const days = Math.floor(sec / 86400);
  const hours = Math.floor((sec % 86400) / 3600);
  console.log(`${days}天${hours}小时`);
});

js代码实现倒计时

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

相关文章

vue实现代码

vue实现代码

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

vue实现网站代码

vue实现网站代码

Vue 实现网站代码的基本步骤 安装 Vue.js 通过 npm 或 CDN 引入 Vue.js。使用 npm 安装:npm install vue。或者直接在 HTML 文件中引入 Vue CDN:…

vue 实现代码

vue 实现代码

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

vue代码框实现

vue代码框实现

Vue 代码框实现方法 在 Vue 中实现代码框功能通常需要结合语法高亮库或 UI 组件库。以下是几种常见实现方式: 使用第三方库 Prism.js 安装 Prism.js 及相关依赖: npm…

vue简单代码实现

vue简单代码实现

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

vue实现动态修改代码

vue实现动态修改代码

Vue 动态修改代码的实现方法 Vue 提供了多种方式实现动态修改代码的需求,以下是几种常见场景和解决方案: 动态组件加载 使用 Vue 的 <component> 标签配合 is 属…