当计时器达到0时,.hide()div

时间:2017-03-14 21:49:37

标签: javascript jquery html countdown

我一直试图让计时器在到达00:00时消失,但每当我尝试它时,它就会立即隐藏div。

以下是我正在使用的代码:



$(document).ready(function(e) {
  var $worked = $("#worked");

  function update() {
    var myTime = $worked.html();
    var ss = myTime.split(":");
    var dt = new Date();
    dt.setHours(0);
    dt.setMinutes(ss[0]);
    dt.setSeconds(ss[1]);

    var dt2 = new Date(dt.valueOf() - 1000);
    var temp = dt2.toTimeString().split(" ");
    var ts = temp[0].split(":");

    $worked.html(ts[1] + ":" + ts[2]);
    setTimeout(update, 1000);
  }

  setTimeout(update, 1000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">00:10</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我为你创造了一个例子。在本例中,我将计时器的间隔更改为10毫秒,以便您可以更快地查看结果。另外,不要在setTimeout函数中设置update以运行update。您可以使用setInterval。我还在更新函数中添加了一个检查,检查时间是否为00:00。如果是,则通过调用clearInterval(timer);并运行$worked.hide()

来使间隔无效

&#13;
&#13;
$(document).ready(function (e) {
        var $worked = $("#worked");
        var timer = setInterval(update, 10);

        function update() {
            var myTime = $worked.html();
            var ss = myTime.split(":");
            var dt = new Date();
            dt.setHours(0);
            dt.setMinutes(ss[0]);
            dt.setSeconds(ss[1]);

            var dt2 = new Date(dt.valueOf() - 1000);
            var temp = dt2.toTimeString().split(" ");
            var ts = temp[0].split(":");
            $worked.html(ts[1]+":"+ts[2]);
            $worked.html(ts[1]+":"+ts[2]);

            if(ts[1] === '00' && ts[2] === '00') {
                clearInterval(timer);
                $worked.hide();
            }
        }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">01:00</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是另一种方法:)

$(document).ready(function(e) {
  var $worked = $("#timer");
  var startTime = new Date().getTime();
  var now, currentDistance;

  setInterval(function update() {
    now = new Date().getTime();
    currentDistance = 10000 - now + startTime;

    if (currentDistance > 0) {
        $worked.html(parseInt(currentDistance / 1000) + " seconds, " + (currentDistance % 1000) + " ms left!");
    } else {
        $worked.hide();
    }
  }, 1);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timer" style="background-color: rgb(190, 190, 220); width: 200px; text-align: center"></div>