How to make Javascript time automatically update

javascript

Solution

Use setTimeout(..) to call a function after a specific time. In this specific case, it is better to use setInterval(..)

function updateTime(){
    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    if (minutes < 10){
        minutes = "0" + minutes
    }
    var t_str = hours + ":" + minutes + " ";
    if(hours > 11){
        t_str += "PM";
    } else {
        t_str += "AM";
    }
    document.getElementById('time_span').innerHTML = t_str;
}
setInterval(updateTime, 1000);

Problem

I am using the following Javascript code to display the time on my website. How can I make this update automatically. Thanks ``` <section class="portlet grid_6 leading"> <header> <h2>Time<span id="time_span"></span></h2> </header> <script type="text/javascript"> var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() if (minutes < 10){ minutes = "0" + minutes } var t_str = hours + ":" + minutes + " "; if(hours > 11){ t_str += "PM"; } else { t_str += "AM"; } document.getElementById('time_span').innerHTML = t_str; </script> </section> ```

Original source

Related problems