Search code examples
javascripttimercountdown

Trying to create a 24 hour timer that resets itself


This is the code I have. Very messy, but due to my inexperience I can't detect why it does not work. By my counts the Decrements are js standard, at least for the milliseconds, seconds and minutes, not sure about the hours.

Here's the code. Thanks in advance.

<!DOCTYPE html>
<html>
<body>

<span id="tHours"></span>:<span id="tMins"></span>:<span id="tSeconds"></span>:<span id="tMilli"></span>

<script>
    var hours = 1;
    var mins = hours * 60;
    var secs = mins * 60;
    var mill = secs * 100;
    var currentHours = 0;
    var currentSeconds = 0;
    var currentMinutes = 0;
    vas currentMilli = 0;
    setTimeout('DecrementMilli()',100);
    setTimeout('DecrementSeconds()',1000);
    setTimeout('DecrementMinutes()',10000);
    setTimeout('DecrementHours()',100000);

    function DecrementMilli() {
        currentMilli = secs % 100;
        if(currentMilli <= 99) currentMilli = "000" + currentMilli;
        secs--;
        document.getElementById("tMilli").innerHTML = currentMilli; 
        if(mill !== -1) setTimeout('Decrement()',100);
    }
        function DecrementSeconds() {
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
        secs--;
        document.getElementById("tSeconds").innerHTML = currentSeconds; 
        if(secs !== -1) setTimeout('Decrement()',1000);
    }
        function DecrementMinutes() {
        currentMinutes = Math.round(secs / 60);
        if(currentMinutes <= 60) currentMinutes = "00";
        mins--;
        document.getElementById("tMins").innerHTML = currentMinutes; 
        if(mins !== -1) setTimeout('Decrement()',10000);
    }
        function DecrementHours() {
        currentHours = Math.round(1440 / 60);
        if(currentHours <= 24) currentHours - 1;
        hours--;
        document.getElementById("tHours").innerHTML = currentHours; 
        if(hours !== -1) setTimeout('Decrement()',100000);
    }
</script>

</body>
</html>

Solution

  • Well, I solved my own problem, but it's inelegant since it does not start at 24:00:00 but at 23:59:59. But it's a start.

    I'll post it here in case it helps anyone

    <script type="text/javascript">
    var count = 86400;
    var counter = setInterval(timer, 1000);
    
    function timer() {
        count = count - 1;
        if (count == -1) {
            clearInterval(counter);
            return;
        }
    
        var seconds = count % 60;
        var minutes = Math.floor(count / 60);
        var hours = Math.floor(minutes / 60);
        minutes %= 60;
        hours %= 60;
    
        document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
    }
    </script>
    
    
    
    <span id='timer'></span>