Simple JavaScript Project with source code | Digital clock
- Last Updated : 9/07/2021
Creating a digital clock in javascript is so simple. If you know how to get the time and call a function continuously for a specific time using javascript, it's really easy for you.
So in this post, we will learn how to create a simple javascript digital clock. To create a javascript digital clock first of all we should know:
- โ How to show data in HTML tag using javascript.
- โ How to get the current date and time in javascript.
- โ How to call a function repeatedly or continuously for a specific time.
How to show data in HTML tag using javascript?
Javascript provides us a very cool method called innerHTML To show data in HTML tag.
Example:
Suppose we have an h1 tag and now we want to show some text inside the h1 tag using javascript, we can do this.
h1.innerHTML = "insideTheDiv";This line will show โinsideTheDivโ text inside the h1 tag.
Note: We will show our time like this to create a digital clock.
<span id="hours"></span> <span>:</span> <span id="minutes"></span> <span>:</span> <span id="seconds"></span> <span id="am-or-pm"></span> document.getElementById("hours").innerHTML=5; document.getElementById("minutes").innerHTML=34; document.getElementById("seconds").innerHTML=45; am_or_pm.innerHTML = 'PM';Download this complte soruce code.
How to get the current date and time using javascript
Getting date and time is so easy in javascript. To create a javascript Date object we can easily get the current date and time.
var dateTime = new Date(); var hours = dateTime.getHours(); var minutes = dateTime.getMinutes(); var seconds = dateTime.getSeconds();Download this complte soruce code.
Note:
๐ Javascript will provide the house value in a global format that means it will count hours 1 to 24, to get the actual value we need to subtract 12 to make it 1 to 12.
๐ To show โAMโ and โPMโ we will check, is our hours greater than 12 or not?
if(hours > 12){ hours = hours - 12; } if(hours >= 12){ // 'PM'; }else{ //'AM'; }Watch this video for a better understanding
Download this complte soruce code.
How to call a function repeatedly or continuously for a specific time
To call a function repeatedly to continuously for a specific time javascript provides us with a method called setInterval(). This method will take two parameters. The first one is our function name which we want to call and the second one is our specific time (in milliseconds).
function updateTime(){ // all code goes here } setInterval( updateTime, 1000); // 1000 milliseconds = 1 secondTo create a javascript digital clock we will call our update time function for every one second so that we can see update time in every second.
Download this complte soruce code.
Still you face problems, feel free to contact with me, I will try my best to help you.