Search code examples
javascriptsetintervalcountdown

Call a Javascript function every second with setInterval


I try to get the function for my JavaScript countdown running every second but somehow I don't get the setInterval function to work.

This is how the JS code looks so far:

// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";

// Get date and time of today
var today = new Date();

// Calculate date and time difference
function getTimeDifference(endtime) {
    var total = Date.parse(endtime) - Date.parse(today);
    var seconds = Math.floor((total/1000) % 60);
    var minutes = Math.floor((total/1000/60) % 60);
    var hours = Math.floor((total/1000/60/60) % 24);
    var days = Math.floor(total/1000/60/60/24);

    
    return {
        total,
        days,
        hours,
        minutes,
        seconds
    };
}


function runCountdown() { 
var t = getTimeDifference(endTimeDate);

document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}

window.setInterval(runCountdown, 1000);

Solution

  • The reason your code is not working as expected because you're declaring today outside of the function which means it's called only once , hence the diff result will always be the same. You probably want to move the assignment and the declaration of var today = new Date(); inside the getTimeDifference function so there will be an actual difference between the enddate value and the today value.

    // Set end date and time
    var enddate = new Date();
    endTimeDate = "2022-01-12 21:52";
    
    // Get date and time of today
    
    // Calculate date and time difference
    function getTimeDifference(endtime) {
    var today = new Date();
    console.log(endtime);
        var total = Date.parse(endtime) - Date.parse(today);
        var seconds = Math.floor((total/1000) % 60);
        var minutes = Math.floor((total/1000/60) % 60);
        var hours = Math.floor((total/1000/60/60) % 24);
        var days = Math.floor(total/1000/60/60/24);
    
        
        return {
            total,
            days,
            hours,
            minutes,
            seconds
        };
    }
    
    
    function runCountdown() { 
    var t = getTimeDifference(endTimeDate);
    
    document.getElementById('days').innerHTML = t.days + " D";
    document.getElementById('hours').innerHTML = t.hours + " H";
    document.getElementById('minutes').innerHTML = t.minutes + " M";
    document.getElementById('seconds').innerHTML = t.seconds + " S";
    }
    
    window.setInterval(runCountdown, 1000);
    <div id="days">
    
    </div>
    <div id="hours">
    
    </div>
    <div id="minutes">
    
    </div>
    <div id="seconds">
    
    </div>