0

I was trying to create a clock following some tutorials on the internet but I'm having a problem. The clock should update itself every second and should show the current time. May I have your help please? This should be the result:https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock . This is my code:

function startClock() {
  var currentTime = new Date();
  console.log(currentTime);

  var currentHours = currentTime.getHours();
  console.log(currentHours);

  var currentMinutes = currentTime.getMinutes();
  console.log(currentMinutes);

  var currentSeconds = currentTime.getSeconds();
  console.log(currentSeconds);

  currentMinutes = checkTime(m);

  currentSeconds = checkTime(s);

  var time = currentHours + ":" + currentMinutes + ":" + currentSeconds;

  document.getElementById("time").innerHTML = time;

  var repeatTime = setTimeout(startClock, 1000);
}

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
    return i;
  }
}
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
Pier
  • 103
  • 1
  • 11

2 Answers2

1

There are four problems in your code:

  1. The startClock() function will call setTimeout() to make sure it gets called again. But it never gets called initially. Thus, add the statement startClock(); at the end, near the </script>.

  2. The variable m does not exist. Fix this by writing currentMinutes = checkTime(currentMinutes);.

  3. The variable s does not exist. Fix this by writing currentSeconds = checkTime(currentSeconds);.

  4. The checkTime() function returns nothing (undefined) if i is not less than 10. Hence, add the statement else return "" + i;.

Fix all of them and it runs! I did test the final result.

Nayuki
  • 17,911
  • 6
  • 53
  • 80
0

Check the gist CurrentTimeData.js

ElSheikh
  • 321
  • 6
  • 28