Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Darrel Lyons
2,991 PointsHelp 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>
1 Answer

Dino Paškvan
Courses Plus Student 44,107 PointsYour 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.
James Barnett
39,199 PointsJames Barnett
39,199 PointsPost all of your code, HTML, CSS and all JS.