倒计时器使用javascript或php的问题

时间:2017-09-06 15:07:38

标签: javascript php

我想要运行此倒计时,但倒计时结束时,它会从24:00:00重新开始。倒计时结束后,我想发送消息或做其他事情。我怎样才能做到这一点?

<div id="hms">00:00:02</div>
<script type="text/javascript">
    var timeoutHandle;
    function count() {
        var startTime = document.getElementById('hms').innerHTML;
        var pieces = startTime.split(":");
        var time = new Date();    time.setHours(pieces[0]);
        time.setMinutes(pieces[1]);
        time.setSeconds(pieces[2]);
        var timedif = new Date(time.valueOf() - 1000);
        var newtime = timedif.toTimeString().split(" ")[0];
        document.getElementById('hms').innerHTML=newtime;
        timeoutHandle=setTimeout(count, 1000);
    }
    count();

</script>

1 个答案:

答案 0 :(得分:0)

我刚刚添加了一个计数器变量,当它为零时,我正在清除超时。看看https://jsfiddle.net/koh9ca6j/1/

您可以通过计算总秒数或任何其他方法来添加条件以检查它何时达到零。

var timeoutHandle;
var counter = 5;

function count() {
  var startTime = document.getElementById('hms').innerHTML;
  var pieces = startTime.split(":");
  //console.log(pieces);
  var time = new Date();
  time.setHours(pieces[0]);
  time.setMinutes(pieces[1]);
  time.setSeconds(pieces[2]);
  var timedif = new Date(time.valueOf() - 1000);
  var newtime = timedif.toTimeString().split(" ")[0];
  document.getElementById('hms').innerHTML = newtime;
  counter--;
  if (!counter) {
    clearTimeout(timeoutHandle);
    return;
  }
}

function countdown() {
  timeoutHandle = setInterval(count, 1000);
}
countdown()