You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为自定义jQuery倒计时函数实现计时结束回调功能

实现方案

你原来的代码有两个问题:一是没有单独的倒计时结束触发逻辑,所有回调每秒都会执行;二是你写的调用方式有语法错误,不需要在传入的函数里再嵌套写callback: function(){}。
下面是修正后的完整实现:

修正后的插件代码

$.fn.countdown = function(toTime, options) {
  let $el = $(this);
  let intervalId;
  // 兼容两种传参:直接传函数则作为结束回调,传对象则分别配置更新、结束回调
  let onUpdate = null;
  let onFinish = null;
  if (typeof options === 'function') {
    onFinish = options;
  } else if (typeof options === 'object') {
    onUpdate = options.onUpdate;
    onFinish = options.onFinish;
  }

  const timeUpdate = () => {
    const now = new Date().getTime();
    const distance = toTime - now;

    // 倒计时结束分支
    if (distance < 0) {
      clearInterval(intervalId);
      $el.html(`0<sup>d</sup> 00:00:00`);
      if (onFinish) onFinish.call($el); // 回调内this直接指向当前倒计时元素
      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);

    // 渲染倒计时内容,用padStart自动补0,简化原来的判断逻辑
    const value = `${days}<sup>d</sup> ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    $el.html(value);

    // 每秒更新时触发的回调,可拿到当前剩余时间数据
    if (onUpdate) onUpdate.call($el, { days, hours, minutes, seconds });
  }

  timeUpdate();
  intervalId = setInterval(timeUpdate, 1000);

  // 返回jQuery对象,支持链式调用
  return this;
};

对应的页面结构不需要改动:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>

调用方法

基础用法(仅配置结束回调)

直接把结束时要执行的函数作为第二个参数传入即可,不需要额外嵌套:

$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime(), function() {
  alert("倒计时结束");
  // 可以直接通过this操作当前倒计时元素,比如显示活动结束文案
  // $(this).html('活动已结束')
});

进阶用法(同时配置更新、结束回调)

如果需要在倒计时每秒刷新时也执行自定义逻辑,可以传入配置对象:

$('#my_div2').countdown(new Date("Jun 23, 2022 22:20:25").getTime(), {
  onUpdate: function(timeData) {
    // 每秒刷新时触发,timeData包含当前剩余的天、时、分、秒数值
    console.log('剩余时间', timeData);
  },
  onFinish: function() {
    console.log('第二个倒计时结束');
    $(this).css('color', 'red');
  }
});

修正点说明

  • 把结束逻辑单独拆分,倒计时归零时只触发一次结束回调,不会重复执行
  • 补全了结束时的归零显示,避免页面出现负数时间
  • 回调内自动绑定当前DOM元素为this,不用额外查找元素
  • 兼容新旧传参方式,原有调用代码不会报错
  • 简化了时间补0的逻辑,代码更易维护

内容的提问来源于stack exchange,提问作者HiDayurie Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 00:54:28