Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Darrel Lyons
Darrel Lyons
2,991 Points

Help with digital clock

Why won't this work? I've just started learning javascript. Every script where i'm using getElement just won't work:

<script type="text/javascript" language="javascript">
function renderTime() {

    var currentTime = new Date();
    var diem = "AM";
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();

    if (h == 0) {
        h = 12;
    }else if (h > 12){
        h = h - 12;
        diem = "PM";
    }
    if (h < 10) { 
        h = "0" + h;
    }
    if (m < 10) {
        m = "0" + h;
    }
    if (s < 10) {
        s = "0" + h;
    }

    var myClock = document.getElementById('clockDisplay');
    myClock.textContent = h + ":" + m + ":" + s " " diem;
    myClock.innerText = h + ":" + m + ":" + s " " diem;
    setTimeout('renderTime()',1000);

}
renderTime();   
</script>
James Barnett
James Barnett
39,199 Points

Post all of your code, HTML, CSS and all JS.

1 Answer

Your code needed a little bit reorganising and some fixing. I've left comments where I changed things:

var myClock = document.getElementById('clockDisplay'); // grab the target div at the top so it's available to the function

function renderTime() {
  var currentTime = new Date();
  var diem = "AM";
  var h = currentTime.getHours();
  var m = currentTime.getMinutes();
  var s = currentTime.getSeconds();

  if (h == 0) {
    h = 12;
  }else if (h > 12){
    h = h - 12;
    diem = "PM";
  }
  if (h < 10) { 
    h = "0" + h;
  }
  if (m < 10) {
    m = "0" + h;
  }
  if (s < 10) {
    s = "0" + h;
  }
  myClock.innerText = h + ":" + m + ":" + s + " " + diem; // this was poorly formatted, some + signs were at wrong places
}

// setInterval will call renderTime() every second, so no need for you to call it manually
// we use it outside of the function so it gets called when the page is ready
// note how the function is passed to setInterval, as a variable, not as a string literal
setInterval(renderTime, 1000); // it's setInterval to repeat something
// you used setTimeout which executes only once after the number of milliseconds passed as the second parameter

If you have any additional questions, feel free to ask.