Search code examples
javascriptweb-frontend

how do i make count down with js for list item?


I have been made a count down for 10 items with JavaScript but it was so long for several items. How can i make this brief? this code for the only one item.

    var time01 = 16360;
    function time(){
        var hour =Math.floor(time01/3600);
        var baghi01=time01%3600;
        var min = Math.floor(baghi01/60);
        var sec = baghi01%60;
        document.getElementById('hour-01').textContent = hour;
        document.getElementById('min-01').textContent = min;
        document.getElementById('sec-01').textContent = sec;
        if(sec<10){
            document.getElementById('sec-01').textContent = (`0${sec}`);
        }
        if(min<10){
            document.getElementById('min-01').textContent = (`0${min}`);
        }
        if(hour<10){
            document.getElementById('hour-01').textContent = (`0${hour}`);
        }
        time01 --;
    }
    setInterval(time,1000);

Solution

  • You could take a closure over the time and target information.

    function time(time, target) {
        const format = v => v.toString().padStart(2, 0);
        var hourE = document.getElementById(`hour-${target}`),
            minE = document.getElementById(`min-${target}`),
            secE = document.getElementById(`sec-${target}`);
    
        return function () {
            var hour = Math.floor(time / 3600)
                baghi01 = time % 3600,
                min = Math.floor(baghi01 / 60),
                sec = baghi01 % 60;
    
            hourE.innerHTML = format(hour);
            minE.innerHTML = format(min);
            secE.innerHTML = format(sec);
            time--;
        };
    }
    
    setInterval(time(16360, '01'), 996);
    setInterval(time(16360, '02'), 997);
    setInterval(time(16360, '03'), 998);
    setInterval(time(16360, '04'), 999);
    setInterval(time(16360, '05'), 1000);
    <span id="hour-01"></span>:<span id="min-01"></span>:<span id="sec-01"></span><br>
    <span id="hour-02"></span>:<span id="min-02"></span>:<span id="sec-02"></span><br>
    <span id="hour-03"></span>:<span id="min-03"></span>:<span id="sec-03"></span><br>
    <span id="hour-04"></span>:<span id="min-04"></span>:<span id="sec-04"></span><br>
    <span id="hour-05"></span>:<span id="min-05"></span>:<span id="sec-05"></span><br>