Help getting my var in javascript to work! (Solved) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help getting my var in javascript to work! (Solved)

this is what i have. function setClock() { var ampm = " "; if (h < 12){ ampm = " AM" }else{ampm = "PM"}; var today = new Date(); var h = today.getHours()%12; var m = today.getMinutes(); var s = today.getSeconds(); m = checkTime(m); s = checkTime(s); document.getElementById('clock').innerHTML = h + ":" + m + ":" + s + ":" + ampm; var t = setTimeout(setClock, 500); } i can't get my ampm var to work. any suggestions on what i am doing wrong? Thanks in advance.

29th Apr 2017, 11:58 PM
Metrik 🕵
Metrik 🕵 - avatar
3 Answers
+ 6
- You are trying to use a variabe before declaring/assigning it ( if (h>12) ) - You don't provide the 'checkTime()' function that you call twice - You need to make a first initial call to the 'setClock()' function to start your 'setTimeout()' loop
30th Apr 2017, 12:10 AM
visph
visph - avatar
+ 5
It looks right ;) With an element id set to "clock", and a first call to your setClock() function, for zwample in the "onload" attribute of <body>: <body onload="setClock();"> <div id="clock"></div> </body> ^^
3rd May 2017, 1:35 AM
visph
visph - avatar
+ 1
Visph Thanks for the help. I think i fixed it. hows this look? var ampm = " "; function setClock() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); m = checkTime(m); s = checkTime(s); if (h < 12){ ampm = " AM" }else{ampm = "PM"}; document.getElementById('clock').innerHTML = h%12 + ":" + m + ":" + s + ":" + ampm; var t = setTimeout(setClock, 500); } function checkTime(i) { if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10 return i; }
3rd May 2017, 12:55 AM
Metrik 🕵
Metrik 🕵 - avatar