3

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>
keune
  • 5,779
  • 4
  • 34
  • 50
jameswildi
  • 31
  • 2
  • 3
  • 7

9 Answers9

13

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);
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
3

Add all your javascript code in a function called updateClock() placed in the <head> section of your page, and alter the <body> tag that way:

<body onload="updateClock(); setInterval('updateClock()', 1000 )">

It will recalculate and redisplay the time every second. Since you only display hours and minutes, you can use a longer interval. If you want to update time every numSeconds you should use something like

<body onload="updateClock(); setInterval('updateClock()', numSeconds * 1000 )">

And of course, this one is just one of many gazillions solutions that you can find out there.

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
1

There are plenty of clock libraries out there. Perhaps check out this previous post: How to create a jquery clock timer

Community
  • 1
  • 1
Recognizer
  • 746
  • 1
  • 7
  • 17
1

try this, a tidier version:

var el = document.getElementById('time_span')
setInterval(function() {

    var currentTime = new Date(),
        hours = currentTime.getHours(),
        minutes = currentTime.getMinutes(),
        ampm = hours > 11 ? 'PM' : 'AM';

    hours += hours < 10 ? '0' : '';
    minutes += minutes < 10 ? '0' : '';

    el.innerHTML = hours + ":" + minutes + " " + ampm;
}, 1000);
Parth Thakkar
  • 5,427
  • 3
  • 25
  • 34
  • avoid `setInterval`: http://weblogs.asp.net/bleroy/archive/2009/05/14/setinterval-is-moderately-evil.aspx – KooiInc May 06 '12 at 15:06
  • Please write the full thing. The title was 'setinterval is (moderately) evil'. I read the whole article. The only major negative point highlighted there was about debugging - which is not a major problem at all, if you use 'Step over' functionality of a debugger. Secondly, I used setInterval because it is executed nomatter whether previous call was executed or not, and since this was about a clock, prev calls don't matter. Actually setTimeout would work perfectly fine over here, it was just intuition that made me use setInterval. – Parth Thakkar May 06 '12 at 16:03
  • And one more thing, which i was forced to state in a separate comment due to limitation of characters, re-registering the function would only add the complexity to the code (though there's hardly any, hehe). So, as I said earlier, it was partly instinct, partly code complexity that made me prefer setInterval. – Parth Thakkar May 06 '12 at 16:05
  • He @Parth, it's all up to you to use `setInterval` or not. Just wanted to point you to some disadvantages. The author summarizes: *replacing setInterval with setTimeout is easy, pain-free and removes the inconveniences of setInterval. So while the setInterval evil is about at the level of not replacing the cap of the toothpaste, the non-evil alternative is so easy that I can’t see a reason not to forget about setInterval for good.* – KooiInc May 06 '12 at 16:17
  • i am convinced that replacing setInterval with setTimeout is dead easy, but I am not convinced in simply putting a label of 'EVIL' on setInterval - at least not in this case. I agree, that using it in game loops or so can be messy, mostly it will, but in something as simple as a clock, I don't think it does any wrong, what say? By the way, aren't we discussing on something silly? :) You opposing setInterval, I favouring it, and the author of the question being happy since he found his solution -- funny situation, no? hehe – Parth Thakkar May 06 '12 at 16:21
  • Yeah, it's a bit of a non subject. I am not *opposed* to `setInterval` and I will never impose anything on anyone, let that be my last word on it ;~) – KooiInc May 06 '12 at 16:34
  • let that be your last word, granted. But please don't leave this habit of imposing something over others - do that. That results in generation of new ideas, as it did in this case. I didn't know about the problems (albeit easily solvable) that could arise while debugging the setInterval-ed code. My word - don't lose that habit, arguments are good. :) – Parth Thakkar May 06 '12 at 16:37
1

GetTime();

function GetTime(){
  var CurrentTime = new Date()
  var hour = CurrentTime.getHours()
  var minute = CurrentTime.getMinutes()
  var second = CurrentTime.getSeconds()

  if(minute < 10){
    minute = "0" + minute
  }

  if(second < 10){
    second = "0" + second
  }

  var GetCurrentTime = hour + ":" + minute + ":" + second + " ";

  if(hour > 11){
    GetCurrentTime += "p.m."
  }else{
    GetCurrentTime += "a.m."
  }

  document.getElementById("CurrentTime").innerHTML = GetCurrentTime;
  setTimeout(GetTime,1000)
}
<span id="CurrentTime"></span>
Sheraff
  • 5,730
  • 3
  • 28
  • 53
Name
  • 11
  • 1
0

A bit less messy would be:

timer();

function timer(){
 var now     = new Date,
     hours   = now.getHours(),
     ampm    = hours<12 ? ' AM' : ' PM',
     minutes = now.getMinutes(),
     seconds = now.getSeconds(),
     t_str   = [hours-12, //otherwise: what's the use of AM/PM?
                (minutes < 10 ? "0" + minutes : minutes),
                (seconds < 10 ? "0" + seconds : seconds)]
                 .join(':') + ampm;
 document.getElementById('time_span').innerHTML = t_str;
 setTimeout(timer,1000);
}

The timer updates (roughly) every second (= 1000 Ms), using setTimeout from within the timer function.

​See it in action

KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

This code output format->00:00:00 and refresh automatically like real time clock, hope it works..

function r(txt) {
    document.write(tex);
}

function createTIME() {
    d = new Date();
    var time = addZERO(d.getHours()) + ':' + addZERO(d.getMinutes()) + ':' + addZERO(d.getSeconds());
    return 'Present Time = ' + time;
}

function doDyn() {
    document.getElementById('Dyn').innerHTML = createTIME();
}

function addZERO(val) {
    return ((val < 10) ? '0' : '') + val;
}
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
0

GetTime();

function GetTime(){
  var CurrentTime = new Date()
  var hour = CurrentTime.getHours()
  var minute = CurrentTime.getMinutes()
  var second = CurrentTime.getSeconds()

  if(minute < 10){
    minute = "0" + minute
  }

  if(second < 10){
    second = "0" + second
  }

  var GetCurrentTime = hour + ":" + minute + ":" + second + " ";

  if(hour > 11){
    GetCurrentTime += "p.m."
  }else{
    GetCurrentTime += "a.m."
  }
<!-- Try changing innerHTML to document.getElementById("CurrentTime").value -->
  document.getElementById("CurrentTime").value = GetCurrentTime;
  setTimeout(GetTime,1000)
}
<span id="CurrentTime"></span>
Rajesh
  • 1
  • 1
-1

timer();

function timer(){
 var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var sec = currentTime.getSeconds()
if (minutes < 10){
    minutes = "0" + minutes
}
if (sec < 10){
    sec = "0" + sec
}
var t_str = hours + ":" + minutes + ":" + sec + " ";
if(hours > 11){
    t_str += "PM";
} else {
   t_str += "AM";
}
 document.getElementById('time_span').innerHTML = t_str;
 setTimeout(timer,1000);
}
<header>
<h2>Time<span id="time_span"></span></h2>
</header>