倒计时开始日期时间,然后倒计时停止日期时间 (jQuery)

Countdown to start datetime, then countdown to stop datetime (jQuery)

如何使用 this countdown library 倒计时到开始时间然后倒计时到停止时间?

文档说我应该将参数 onExpiry 添加到 运行 回调函数,但无论我如何构造这些函数,它要么开始倒计时到 stopdate,即使 startdate 仍在未来 它停在 00:00:00:00 并且在 startdate.

到期时不做任何事情

我需要它做的是 startdate 倒计时,完成后,倒计时 stopdate

function startTimers() {
  $(function() {
    $('#auction-counter').countdown({
      until: startdate,
      onExpiry: stopTimer,
      format: 'DHMS',
      padZeroes: true,
      alwaysExpire: true
    });

    function stopTimer() {
      $('#auction-counter').countdown({
        until: stopdate,
        format: 'DHMS',
        padZeroes: true,
        alwaysExpire: true
      });
    }
  });
}

上面的代码倒计时到 startdate 但随后在 00:00:00:00

处停止

您的代码即将生效。您遇到的问题是需要从 #auction-counter 元素中删除原始倒计时实例。这可以使用倒计时插件的 destroy 设置来完成。

从那里您可以使用 stopdate 重新初始化第二次倒计时,如下所示:

// date setup
let now = new Date();
let startdate = new Date(now.setSeconds(now.getSeconds() + 5));
let stopdate = new Date(now.setSeconds(now.getSeconds() + 5));
let $counter = $('#auction-counter');

function firstTimer() {
  $counter.countdown({
    until: startdate,
    onExpiry: secondTimer,
    format: 'DHMS',
    padZeroes: true,
    alwaysExpire: true
  });
}

function secondTimer() {
  $counter.countdown('destroy'); // destroy original countdown instance
  
  console.log('starting second countdown');  
  $counter.countdown({
    until: stopdate,
    onExpiry: () => console.log('both timers complete!'),
    format: 'DHMS',
    padZeroes: true,
    alwaysExpire: true
  });
}

firstTimer();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.1.0/js/jquery.plugin.min.js" integrity="sha512-MPI2h+3IVJR8ElOGFV02uH6W1augIqS9y/YgTZH7xNb7QwLVPjFL0eRxbDpE6ZAk/hQbHm6zWXMh/oMR4/3sDA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.1.0/js/jquery.countdown.min.js" integrity="sha512-+Cdr05lT+aP+PTW4988XKLMjoAf0o5P2nRDIHooD/NItysfsyCPPhZhK/C6s7ZpaVoMRtsvRNJLtYOTDANC5UA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.1.0/css/jquery.countdown.min.css" integrity="sha512-3TZ6IiaoL7KEeLwJgOfw+/dEOxOUpb9YhmUokvcFOvNuFJ7t9kvilMNAMqeJ8neRT4iBnCe35TZsPwD2Y1Gl6g==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div id="auction-counter"></div>