在特定时间重新开始倒计时

时间:2020-09-20 12:47:57

标签: php html jquery

我有多个倒数计时器和一个正在运行的实时数字时钟。我正在使用jQuery.countdown脚本库http://hilios.github.io/jQuery.countdown/documentation.html进行倒计时。当我的倒数结束或达到00:00:00时,我停止倒数并显示'00:00:00'。这没有问题。但是我想要的是在特定时间之后,假设数字时钟是08:00:00,我想重新开始倒计时。 jQuery.Countdown库具有暂停/启动功能,也许这是我需要的,但我不知道如何实现。

<div id="realtime-digiclock">08:00:00</div>

<?php
$dateToday = date("Y-m-d");
?>

<span class="countdown" value="<?php echo $dateToday; ?> 00:10:00"></span>
<span class="countdown" value="<?php echo $dateToday; ?> 00:20:00"></span>
<span class="countdown" value="<?php echo $dateToday; ?> 00:30:00"></span>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/hilios/jQuery.countdown@master/dist/jquery.countdown.min.js"></script>

<script>
            
$(function(){        
      $('.countdown').each(function(){
         $(this).countdown($(this).attr('value'), function(event) {
         $(this).text(event.strftime('%H:%M:%S'));
      }).on('finish.countdown', function(e) {
          $(this).text("00:00:00");
        });
    });
 });   
</script>
    <!-- Digiclock - https://jquerycards.com/forms/date-time/jclocksgmt-js/--> 
<script>
 $(function(){ 
  $('#realtime-digiclock').jClocksGMT({ title:'', offset:'-4', timeformat:'hh:mm:ss a', skin: 2, analog: false });
    });                 
</script>

1 个答案:

答案 0 :(得分:0)

我检查了jQuery.Countdown docs,但没有提到“重置”功能。 但是,如果您检查source code in countdown.js,就会发现除了文档中提到的方法以外,还有几种方法可以使用-您需要的方法是.setFinalDate(value)- >,因为您可以在倒计时停止时进行重写。

例如,假设您有一个倒数计时器(#countdown1),您想在倒数结束时对其进行“重置”。假设timeNow = 2020-09-20 17:00:00deadline1 = 2020-09-20 17:00:10。倒数计时器将运行 10秒,然后设置finish.countdown事件并停止。此刻,您想将其下一次“重置”:deadline2 = 2020-09-20 17:00:20,因此计时器将再运行另外10秒。此示例所需的代码如下:

这是jsfiddle working demo

<!-- resources -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<script src="https://cdn.jsdelivr.net/gh/hilios/jQuery.countdown@master/dist/jquery.countdown.min.js"></script>
<!-- demo html - one countdown -->
<span id="countdown1" value=""></span>

<script>
/* demo vars...*/
var timeNow = (new Date()).getTime();
var deadline1 = timeNow + 10 * 1000; // after 10 seconds
var deadline2 = timeNow + 20 * 1000; // after 20 seconds (10 seconds after first deadline)
/* setup the countdown */
$("#countdown1").countdown(deadline1, function (event) {
      $(this).text(event.strftime("%H:%M:%S"));
    })
.on("finish.countdown", function(e){
  var $target = $(this);
  if (e.timeStamp < deadline2) {
    alert("First deadline reached! -> continue to next one...");
    /** RESET THE COUNTDOWN -> .setFinalDate() method **/
    $target.countdown("setFinalDate", deadline2);
    /** RESTART THE COUNTDOWN **/
    $target.countdown("start")
  } else {
    alert("Second deadline reached! -> END");
  }
});
</script>

我希望这个演示会为您提供帮助。