当前位置:首页 > JavaScript

js实现自定义倒计时器

2026-01-31 12:19:42JavaScript

实现自定义倒计时器的核心逻辑

通过 Date 对象获取时间差,利用 setInterval 动态更新显示。以下是一个基础实现方案:

js实现自定义倒计时器

function startCountdown(targetTime, displayElement) {
  const interval = setInterval(() => {
    const now = new Date().getTime();
    const distance = targetTime - now;

    if (distance <= 0) {
      clearInterval(interval);
      displayElement.textContent = "倒计时结束";
      return;
    }

    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    displayElement.textContent = `${days}天 ${hours}时 ${minutes}分 ${seconds}秒`;
  }, 1000);
}

// 使用示例:倒计时至2023年12月31日
const targetDate = new Date("2023-12-31T00:00:00").getTime();
startCountdown(targetDate, document.getElementById("countdown"));

优化性能的实现方式

使用 requestAnimationFrame 替代 setInterval 避免时间漂移:

js实现自定义倒计时器

function smoothCountdown(targetTime, displayElement) {
  function update() {
    const now = Date.now();
    const distance = targetTime - now;

    if (distance <= 0) {
      displayElement.textContent = "时间到!";
      return;
    }

    const totalSeconds = Math.floor(distance / 1000);
    const days = Math.floor(totalSeconds / 86400);
    const hours = Math.floor((totalSeconds % 86400) / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    displayElement.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;
    requestAnimationFrame(update);
  }
  update();
}

添加暂停/继续功能

通过闭包保存计时器状态:

function createCountdownController(targetTime, displayElement) {
  let timer = null;
  let remainingTime = targetTime - Date.now();

  return {
    start() {
      if (timer) return;

      const endTime = Date.now() + remainingTime;
      timer = setInterval(() => {
        remainingTime = endTime - Date.now();
        if (remainingTime <= 0) {
          clearInterval(timer);
          displayElement.textContent = "完成";
        } else {
          displayElement.textContent = formatTime(remainingTime);
        }
      }, 1000);
    },
    pause() {
      clearInterval(timer);
      timer = null;
    }
  };
}

function formatTime(ms) {
  // 时间格式化逻辑同上
}

支持回调函数的扩展实现

允许在特定事件触发时执行回调:

function advancedCountdown(options) {
  const {
    duration,
    onUpdate,
    onComplete,
    interval = 1000 
  } = options;

  let startTime = Date.now();
  let expected = startTime + interval;
  let timeoutId;

  const step = () => {
    const elapsed = Date.now() - startTime;
    const remaining = Math.max(0, duration - elapsed);

    if (remaining <= 0) {
      onComplete?.();
      return;
    }

    onUpdate?.(remaining);

    const drift = Date.now() - expected;
    expected += interval;
    timeoutId = setTimeout(step, Math.max(0, interval - drift));
  };

  timeoutId = setTimeout(step, interval);

  return {
    stop() {
      clearTimeout(timeoutId);
    }
  };
}

注意事项

  1. 时区处理:new Date() 使用本地时区,建议用 UTC 时间或明确指定时区
  2. 内存泄漏:清除不再需要的定时器
  3. 性能优化:频繁 DOM 操作建议使用文档片段或防抖
  4. 跨标签页同步:考虑使用 BroadcastChannellocalStorage 事件保持多页面同步

分享给朋友:

相关文章

vue实现自定义事件

vue实现自定义事件

Vue 自定义事件实现方法 在 Vue 中,自定义事件是通过 $emit 方法触发的,父组件通过 v-on 或 @ 监听子组件触发的事件。以下是几种常见的实现方式: 子组件触发事件 在子组件中…

vue实现计时器

vue实现计时器

实现计时器的基本逻辑 在Vue中实现计时器通常需要利用setInterval或setTimeout来更新计时状态,并通过Vue的响应式系统动态显示时间。计时器的核心是记录开始时间、暂停时间以及计算当前…

vue 计时器实现

vue 计时器实现

Vue 计时器实现方法 使用 setInterval 实现基础计时器 在 Vue 组件的 data 中定义计时器变量和当前时间: data() { return { timer: nul…

react 如何自定义事件

react 如何自定义事件

自定义事件的基本概念 在 React 中,自定义事件通常指通过组件间传递回调函数或使用 Context API、事件总线等方式实现的通信机制。React 本身不直接支持类似 DOM 的 CustomE…

react如何自定义右键菜单

react如何自定义右键菜单

自定义右键菜单的实现方法 在React中实现自定义右键菜单通常涉及监听contextmenu事件、阻止默认行为并渲染自定义菜单组件。以下是具体实现方式: 监听右键点击事件 在目标元素上添加onCon…

react如何删除自定义的组件

react如何删除自定义的组件

删除自定义组件的步骤 在React中删除自定义组件需要从代码中移除其定义和所有引用。以下是具体操作方法: 移除组件引用 检查项目中所有使用该组件的地方,包括其他组件、页面或测试文件,删除所有imp…