How to display current time using javascript

Okay, so here’s another quick tip. Let me show you how you can build a digital clock which updates without refreshing the page.


Building the function

First let’s build the function which will output the date:

function tym(){

var date = new Date();
var hr = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
document.getElementById("time").innerHTML =  hr + " : " + min + " : " + sec;


I said I’ll make this quick but I’ll still explain this one to you. First we created a function called tym().
Then we declared an object for the Date javascript class. (I called it class because it really looks like a class to me, so correct me in the comments if you think I’m wrong). We then break down the date into hours, minutes and seconds and assigned them to their very own variables.

Basically, getHours(), getMinutes(), and getSeconds(). As their format suggests, are functions inside the Date class which returns what the hours, minutes and seconds. So all we have to do is to spit them out on the screen to see their contents.

On the last line, what we did was just to output the things that we have gathered so far.



Here’s the little piece of code which will serve as a container for the time:

<div id="time">




Lastly, let’s call the function that we created earlier:

document.onload = setInterval("tym()",100);

setInterval is a javascript function which takes two parameters:

  • function
  • time interval – 100 is like 1 second. Don’t take my word for it, I’m not really sure if its 1 second or less.



The output will be like a digital clock, which ticks every second without refreshing the page.

One thought on “How to display current time using javascript

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s