1

Bear with my crappy JS skills, but I'm trying to get a page to update with moment.js so it continually shows the seconds count.

I have this:

function update_time(){ 

 var now = moment().format('h:mm:ss a');

$('.timer').append(now);

setTimeout(update_time, 1000);

})();

Yet I'm not sure how to get it to work correctly. I'm pretty sure I'm not closing something correctly, or even if I have the function formatting correctly.

ultraloveninja
  • 1,969
  • 5
  • 27
  • 56
  • Not sure if it's due to error in copy-paste - but shouldn't there be a '(' before function? Also, can you provide more information on how is it working incorrectly? – linstantnoodles Dec 05 '13 at 00:09

3 Answers3

2

There seems to be two issues here.

First, your self-invoking function needs to be surrounded by parentheses; you seem to be missing the first opening parenthesis as @linstantnoodles pointed out.

Second, appending the time will keep appending the time text to the given node every second. You probably want to replace the content of .timer, so you should use jQuery.text() instead.

Here's a fiddle.

(function update_time(){ 
    var now = moment().format('h:mm:ss a');
    $('.timer').text(now);
    setTimeout(update_time, 1000);
})();
Thomas Upton
  • 1,853
  • 12
  • 22
  • 1
    I think you mean [`.text()`](http://api.jquery.com/text/). It might not make a difference in this case, but `.html()` should only be used with an HTML-encoded string. – quietmint Dec 05 '13 at 00:44
  • Thanks Thomas! Yeah, I'm piecing together some items from other resources and I haven't really worked with custom JS functions that much. I wasn't really sure how to set it up from scratch. But this really helps me understand it better and it's working. Thanks! – ultraloveninja Dec 05 '13 at 13:03
  • Good call, @user113215. Either works, but `.text` is more appropriate here. – Thomas Upton Dec 05 '13 at 19:43
0

Try this one:

function update_time(){        
  var now = moment().format('h:mm:ss a');    
  //displaying the timer    
  $('.timer').html(now);    
  //Keeping update in seconds    
  setTimeout(update_time, 1000);    
};

//Initiate first
setTimeout(update_time, 1000);
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
ruel
  • 1
  • 1
0

You shouldn't rely on the method setTimeout() when doing clock work (see question). Instead use the date object like in the sample at W3schools or see script like http://flipclockjs.com/ for accurate timers.

Community
  • 1
  • 1
TJ-
  • 116
  • 10