How to Display live Clock With JavaScript in simple Steps

How to Display live Clock With JavaScript in simple Steps


Hey guys in this tutorial you will learn how to create  a live Clock with JavaScript. We will only Plain use JavaScript and no External libraries. So let's get Started.




First of all Create a Basic HTML Template with all the Basic Tags. In the Template give the Title as Live clock with JavaScript.


In the <Body> Tag add a Paragraph tag and give it an id of result as shown below

<p id="result"></p>


This Id will be used to display the Live Clock using javascript function. Now our HTML part is over. Yes! That's it for HTML part. Now all we have to do is add a JavaScript code that will display the clock in our Paragraph tag which we assigned the id of result.


Next, add the following code below the paragraph tag. You can also add this to the <head> Tag.

<script type="text/javascript">

var timer = setInterval(showclock,100);

function showclock(){

var d = new Date();

var time = d.toLocaleTimeString();

document.getElementById('result').innerHTML=time;

}

var timer = setInterval(showclock,100);

</Script>


This above code will display a Live Clock Which will update every 100 milliseconds. You can add this clock in your projects or any web App.

Explanation of the JavaScript Code:

First we define a function named showclock()

Inside the function, we declare a variable d which contains an instance of Date() object in JavaScript.


Next, we create one more variable time which contains the current time. We obtain the current time using toLocaleTimeString() method.


Once we get the current time, we update it to the paragraph element with the id result which we decided in the <body> Tag.


Bonus tip : if you want to display current date just use toLocaleDateString() method.


Final code should look something like this:


<!DOCTYPE html>


<html>

<head>

<title>JavaScript Live clock</title>

</head>

<body>

<p id="result"></p>

<script type="text/javascript">

var timer = setInterval(showclock,100);

function showclock(){

var d = new Date();

var time = d.toLocaleTimeString();

document.getElementById('result').innerHTML=time;


}


var timer = setInterval(showclock,100);


</script>


</body>


</html>






See the Output here here





you might also like: how to create Javascript Countdown in simple steps


0 Comments: