在if else语句中在JavaScript中运行回调



我有此代码段,当我的$remainingTime变为零时,我希望它在回调中运行停止函数。我不知道我在其他语句中必须写些什么。

var clock = $('.clock').FlipClock(
  <?php
  $now = new DateTime('now');
  $tm = new DateTime('2017-12-22 12:00:00');
  $remainingTime = $tm->getTimestamp()-$now->getTimestamp();
  if($remainingTime>0) {
    echo $remainingTime;
  } else {
  }
  ?>
  ,{
    clockFace: 'DailyCounter',
    countdown: true,
  callbacks: {
    stop: function() {
      $(".timerContainer").css('display','none');
    }
  }
});

在插件代码之后放置检查。

var clock = $('.clock').FlipClock(
  <?php
  $now = new DateTime('now');
  $tm = new DateTime('2017-12-22 12:00:00');
  $remainingTime = $tm->getTimestamp()-$now->getTimestamp();
  if($remainingTime>0) {
    echo $remainingTime;
  } else {
  }
  ?>
  ,{
    clockFace: 'DailyCounter',
    countdown: true,
  callbacks: {
    stop: function() {
      $(".timerContainer").css('display','none');
    }
  }
});
<?php if ($remainingTime == 0) {
    ?>
    $(".timerContainer").hide();
<?php }

我不会以这种方式混合JS和PHP。您可以做类似的事情:

<script>
  function runClock(remainingTime) {
    $('.clock').FlipClock(remainingTime, {
      clockFace: 'DailyCounter',
      countdown: true,
      onStop: function () {
        $(".timerContainer").css('display', 'none');
      }
    });
  }
</script>
<?php
$now = new DateTime('now');
$tm = new DateTime('2017-12-22 12:00:00');
$remainingTime = $tm->getTimestamp() - $now->getTimestamp();
if ($remainingTime > 0) {
  echo "<script> runClock(" . $remainingTime . ");</script>";
}
?>

简单地您可以使用setInterval并计数直到达到时间:例如,要运行10秒的代码段:

    var i = 10;
    var end = 15;
    var statusDiv = document.getElementById("status");
    
    var t = setInterval(function(){ 
      if(i++ >= end) {
        clearInterval(t);
        stop();
       }
       statusDiv.innerHTML = i;
    }, 1000);
    
    
    function stop(){
      alert("stopped, Now 'i' equals " + i);
    }
<div id="status"></div>

我不确定FlipClock在做什么,但看来就像一个计数器一样JavaScript,检查以下片段:

var d1 = new Date(); //"now"
var d2 = new Date("December 23, 2017 01:13:00")  // some date
//var d2= new Date(2017,12,23,1,13,0);//same as d2 above
var remainingTime = Math.abs(d1-d2);  // get the diff in milliseconds

最新更新