How to set vanilla js clock app to automatically update without reloading the page

I’ve built this simple app using vanilla JavaScript but I can’t find out how to set it to automatically update without having to reload the page, does anyone know how I can do this? Thank you all in advance!

setInterval(function(){ 
    timeNow();
}, 1000)

function timeNow() {
    const dateObj = new Date();
    const weekDays = {
        '0': 'Sunday',
        '1': 'Monday',
        '2': 'Thursday',
        '3': 'Wednesday',
        '4': 'Thursday',
        '5': 'Friday',
        '6': 'Saturday'
    }
    const months = {
        '0': 'JAN',
        '1': 'FEB',
        '2': 'MAR',
        '3': 'APR',
        '4': 'MAY',
        '5': 'JUN',
        '6': 'JUL',
        '7': 'AUG',
        '8': 'SEP',
        '9': 'OCT',
        '10': 'NOV',
        '11': 'DEC'
    }
    let year = dateObj.getFullYear();
    yearElement.innerHTML = year;
    let hour = dateObj.getHours() <= 9 ? '0' + dateObj.getHours() : dateObj.getHours();
    let min = dateObj.getMinutes() <= 9 ? '0' + dateObj.getMinutes() : dateObj.getMinutes();;
    let sec = dateObj.getSeconds() <= 9 ? '0' + dateObj.getSeconds() : dateObj.getSeconds();
    hourElement.innerHTML = hour + ':' + min + ':' + sec;
    let date = dateObj.getDate()
    dateElement.innerHTML = date;
    let day = weekDays[dateObj.getDay()];
    daysElement.innerHTML = day;
    let month = months[dateObj.getMonth()];
    monthElement.innerHTML = month;
    console.log(sec);
}

Answer

Try using setInterval function to get your date at every 1000ms. setInterval(function(){ console.log(display.getCurrentTime()); }, 1000);

Leave a Reply

Your email address will not be published. Required fields are marked *