1

I am using the following script for showing the current time on my website:

<script type="text/javascript">
<!--

    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    if (minutes < 10)
        minutes = "0" + minutes
    var suffix = "AM";
    if (hours >= 12) {
        suffix = "PM";
        hours = hours - 12;
    }
    if (hours == 0) {
        hours = 12;
    }

    document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
//-->
</script>

However, I need to refresh the page in order for the time to update. Can I have the time refresh every minute automatically so it stays up to date?

Thanks.

Bic
  • 3,141
  • 18
  • 29
user3353117
  • 33
  • 1
  • 5
  • I recommend you look at using [Livestamp.js](http://mattbradley.github.io/livestampjs/) – Engineer2021 Feb 25 '14 at 20:47
  • Thanks. I was hoping if possible to use the existing code already in place.I was looking at a function like setInterval but it requires my existing script to be wrapped in a function. I tried that and it broke. Perhaps I am doing it wrong? – user3353117 Feb 25 '14 at 20:50
  • I don't see a point in rolling your own.. years ago you had to but use a library if its available. – Engineer2021 Feb 25 '14 at 20:51

1 Answers1

0

You can use setInterval to have that code execute every x milliseconds:

function setTime() {
    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    if (minutes < 10)
        minutes = "0" + minutes
    var suffix = "AM";
    if (hours >= 12) {
        suffix = "PM";
        hours = hours - 12;
    }
    if (hours == 0) {
        hours = 12;
    }

    document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
}

setInterval(setTime, 60000);

Note, it is generally a bad practice to use document.write. A better approach would be to have the displayed element statically on the page, and update it in the method.

document.getElementById('currentTime').innerText = hours + ":" + minutes + " " + suffix; 

Here is a working Fiddle Demo

Bic
  • 3,141
  • 18
  • 29
  • Thanks very much! This works well in Chrome, but the time disappears in Firefox for me. Any suggestions? – user3353117 Feb 25 '14 at 21:00
  • Use `textContent` instead of `innerText`. I believe this is more cross-browser compatible. Check out [This Answer](http://stackoverflow.com/questions/11646398/cross-browser-innertext-for-setting-values) for making something that will work in multiple browsers. – Bic Feb 25 '14 at 21:02
  • It works great in Firefox now, but on Android with the default browser I'm still not getting anything. Is there something different required for that? – user3353117 Feb 25 '14 at 21:09
  • Apparently, Android browser supports `innerHTML`. I don't do a lot mobile web development, so I am not sure what the approach to take for that would be. – Bic Feb 25 '14 at 21:13