Search code examples
javascripthtmlcsscountdown

Creating a custom countdown


So I am creating a custom page opening countdown and I am wondering how do I create the JavaScript part?

This is my JavaScript

function start() {
    var openDate = new Date(2013, 7, 24);
    setInterval(function () {
        var today = new Date();
        var delta = openDate - today;
        var days = Math.floor(delta / 86400).toString();
        var hours = (Math.floor(delta / 3600) % 24).toString();
        var minutes = (Math.floor(delta / 60) % 60).toString();
        var seconds = (delta % 60).toString();

        $(".seconds#first").text(seconds[0]);

    }, 1000);
}

This works, but the values are off. I don't know what to do. This is my HTML also if it helps.

<div id="countdown">
    <ul class="days">
        <li id="first">1</li>
        <li id="second">1</li>
        <li id="third">1</li>
    </ul>
    <ul class="hours">
        <li id="first">1</li>
        <li id="second">1</li>
    </ul>
    <ul class="minutes">
        <li id="first">1</li>
        <li id="second">1</li>
    </ul>
    <ul id="last" class="seconds">
        <li id="first">1</li>
        <li id="second">1</li>
    </ul>
</div>

Solution

  • When you subtract two date values in JavaScript, the returned value is always in milliseconds. This means that the value of the variable delta would be in milliseconds and that is what was causing the issue as the rest of your code is written with the assumption that the return value is in seconds.

    To overcome this, the delta value should be divided by 1000 (to convert it to seconds) and the Math.floor function should be used in the calculation of the seconds value also because millisecond to seconds conversion could result in fractional values.

    var openDate = new Date(2015, 7, 24);
    
    setInterval(function () {
    
        var today = new Date();
        var delta = (openDate - today) / 1000; //to convert to seconds
        var days = Math.floor(delta / 86400).toString();
        var hours = (Math.floor(delta / 3600) % 24).toString();
        var minutes = (Math.floor(delta / 60) % 60).toString();
        var seconds = (Math.floor(delta % 60)).toString();
    
        document.getElementById("first").innerHTML = "Days: " + days + "  Time: " + hours + " : " + minutes + " : " + seconds;
    
    }, 1000);
    <div id="first"></div>

    JavaScript Date Object - MDN Reference