How to make a display of a clock synchronous with the real time

I want to make a clock with javascript.

I want that the seconds and even milliseconds are displayed in real time, like a real clock. That you can see how the numbers are changing in real time.

I thought about a loop where a function is calling itself to repeat the write command like this one

function countdown (i) {
  if (i == undefined) {
    i = 10;
  }

  if (i > 0) {
    i--;
    var timeout = window.setTimeout("document.getElementById("thedate").innerHTML ... , 1000);
  }
}
countdown();

And how can I make it that the function is repeating itself in the same speed like the real clock, is this even possible?

When I just set the step intervall of setTimeout at 1 and repeat the function 1000 times per second it is maybe asynchronous with the real time I defined before by getDate, am I right?

The main question is: how can I get my repeating function synchron with the real time?

Answers:

Answer

Use the setInterval Web Api for that problem:

var intervalID = window.setInterval(myCallback, 1000);

function myCallback() {
  // Gets called every second
}

Documentation for the setInterval() method

Answer

In my blog , you can find exactly what you want

http://turgaygulmez.com/javascript-local-time/

Answer

Instead of creating infinite loop with function, just use setInterval(function () {}, 1000);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.