Search code examples
javascriptjqueryhtmlcountdown

.hide() div when timer reaches 0


I have been trying to make a timer disappear when it reaches 00:00 but everytime I try something it just hides the div right away.

Here is the code I am using:

$(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>


Solution

  • I have created an example for you. For this example I have changed the timer's interval to 10ms so you can see the result quicker. Also instead of setting a setTimeout to run update inside the function update. You can use setInterval. I have also added a check inside the update function that checks if the time is 00:00. If it is true, then it invalidates the interval by calling clearInterval(timer); and runs $worked.hide()

    $(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();
                }
            }
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="worked">01:00</div>