6

I want to show the current time on a website I am making for class, but I cannot find a way to do so. Is their a way to show real time in code? and if so, how do you do it?

Kakers
  • 63
  • 1
  • 1
  • 4

1 Answers1

14

You can accomplish this fairly easily by first creating an element:

<span id="clock"></span>

And then getting a reference to that element:

var clockElement = document.getElementById( "clock" );

Next we'll need a function that will update the contents with the time:

function updateClock ( clock ) {
    clock.innerHTML = new Date().toLocaleTimeString();
}

Lastly, we'll want to make sure we're calling this every second to keep the clock up to date:

setInterval(function () {
    updateClock( clockElement );
}, 1000);

So when we put it all together it looks like this:

(function () {

  var clockElement = document.getElementById( "clock" );

  function updateClock ( clock ) {
    clock.innerHTML = new Date().toLocaleTimeString();
  }

  setInterval(function () {
      updateClock( clockElement );
  }, 1000);

}());
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • Such an elegant way of doing. I know this is an old post. But I am just curious what is that special `(function () {}());` structure? I am not an expert in Javascript and jQuery – Anu Jun 04 '21 at 01:37
  • The function structure is called IIFE (Immediately Invoked Function Expression). It's a function that calls itself. MDN has a helpful overview - https://developer.mozilla.org/en-US/docs/Glossary/IIFE – Sean Kelliher May 01 '23 at 20:13