0

On my website, I want the time to be shown live and update automatically without needing to refresh the page.

I have in the header of index.php the following:

<script src="/../scripts/time.js"></script>

time.js is the script below:

var currentTime = new Date(),
      hours = currentTime.getHours(),
      minutes = currentTime.getMinutes();
    if (minutes < 10) {
     minutes = "0" + minutes;
  }
    document.write(hours + ":" + minutes)

It indeed shows correctly the current time, but it does not update without refreshing/reloading the web page. I believe it should actually be updating automatically since it is in JavaScript (which is known to able to do so).

What might I have done wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Job
  • 3
  • 5
  • JS not automatically update. Your answer in [How to make Javascript time automatically update](https://stackoverflow.com/questions/10470825/how-to-make-javascript-time-automatically-update) – Minh Nguyen Jan 15 '19 at 01:37

1 Answers1

0

You only took the currentTime once. You have to get them by "intervals". Here's an example code taken from w3schools.com: Window clearInterval() Method:

<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar = setInterval(myTimer, 1000);

function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
  clearInterval(myVar);
}
</script>

</body>
</html>

See the running code here.

Note: Intentionally gave the clearInterval() example to give a step further to grasping the idea.

Alex Pappas
  • 2,377
  • 3
  • 24
  • 48
  • thanks this worked! I simply copied that script from the 'Tryit Editior' of w3schools and it works now! – Job Jan 15 '19 at 13:15