how to update time regularly?

There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope.

Also, the use of document.write is discouraged.

Here’s how I would do it:

JavaScript:

function updateClock() {
    var now = new Date(), // current date
        months = ['January', 'February', '...']; // you get the idea
        time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea

        // a cleaner way than string concatenation
        date = [now.getDate(), 
                months[now.getMonth()],
                now.getFullYear()].join(' ');

    // set the content of the element with the ID time to the formatted string
    document.getElementById('time').innerHTML = [date, time].join("https://stackoverflow.com/");

    // call this function again in 1000ms
    setTimeout(updateClock, 1000);
}
updateClock(); // initial call

HTML:

<div id="time"> </div>

Leave a Comment