16
function timeClock()
{
    setTimeout("timeClock()", 1000);        
    now = new Date();
    alert(now);
    f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
    return f_date;
}

<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>

alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?

alex
  • 163
  • 1
  • 1
  • 4

10 Answers10

44

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(' / ');

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

HTML:

<div id="time"> </div>
Community
  • 1
  • 1
Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
6

setInterval(expression, timeout);

The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.

I would rewrite Ivo's answer as follows:

JavaScript:

function updateClock() {
  // Ivo's content to create the date.
  document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);

Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/

Aaron Votre
  • 1,620
  • 1
  • 12
  • 8
0

Straigt Javascript time format / update

1: create month converter func 2: create time func 3: create update func 4: create outPut func

    // month converter from index / 0-11 values
function covertMonth(num){
  let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  // look into index with num 0-11
  let computedRes = months[num];
  return computedRes;
}

// time func
function Time(){
   // important to get new instant of the Date referrance
  let date = new Date();
  this.time = date.toLocaleTimeString();
  this.year = date.getUTCFullYear();
  this.day = date.getUTCDate();
  this.month = date.getUTCMonth();
  this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
  return this.currentTime;
}


 function timeOutPut(){
  let where = document.getElementById('some-id');
  where.textContent = Time(); // 1:21:39 AM Dec 17 2017
}

   // run every 5secs
setInterval(timeOutPut, 5000);
soloproper
  • 31
  • 6
0
x = document.getElementsByTagName('SPAN').item(0);
x.innerHTML = f_date;

try putting this code block instead of return statement, i haven't test it but it will probably work

Yunus Eren Güzel
  • 3,018
  • 11
  • 36
  • 63
  • First time documrnt.write is showing the undefined value.[ 23 Feb 2011 / 7.47 PM ISTundefined]. After a second it shows me the correct value. – alex Feb 23 '11 at 14:16
0

There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...

http://timeago.yarp.com/

Tim Reddy
  • 4,340
  • 1
  • 40
  • 77
0
$('span.foo').html(f_date);

place this inside your timeclock() function

untested

    function timeClock()
    {
        setTimeout("timeClock()", 1000);        
        now = new Date();
        alert(now);
        f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
       $('span.foo').html(f_date);

}
Rafay
  • 30,950
  • 5
  • 68
  • 101
0

I'd use setInterval rather than setTimeout:

https://developer.mozilla.org/en/DOM/window.setInterval

Abderrahmane TAHRI JOUTI
  • 3,514
  • 2
  • 26
  • 43
  • 1
    it is advised to avoid `setInterval()` have a look here http://weblogs.asp.net/bleroy/archive/2009/05/14/setinterval-is-moderately-evil.aspx – Rafay Feb 23 '11 at 14:15
0

I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.

I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.

http://jsfiddle.net/5JWEV/

BenWells
  • 317
  • 1
  • 10
0

I used @soloproper setInterval concept @Ivo Wetzel overall answer, my update is all about formatting the time as required. Reduced Programming Lines

<div id="liveClock"> </div>

$(document).ready(function () {
        updateClock();
});

function updateClock() {
   document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
}
setInterval(updateClock, 1000);
Pranesh Janarthanan
  • 1,134
  • 17
  • 26
-1
function timeClock()
{
    setTimeout("timeClock()", 1000);        
    now = new Date();
    alert(now);
    f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());

    document.getElementById("foo").innerHTML = f_date;

}

<span id="foo"></span>
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456