DEV Community

Cover image for How to create digital clock in Vanilla JS
ahmadullah
ahmadullah

Posted on

How to create digital clock in Vanilla JS

I can create a digital clock in two ways the first one is using setInterval method.
digitalclock
And the second way is using setTimeout function but a little bit confusing and challenging.

Creating digital clock using setInterval

HTML Part

<h1 class='time'></h1>
Enter fullscreen mode Exit fullscreen mode

CSS Part

body {
display:flex;
align-items:center;
justify-content:center;
height:100vh;
background-color:#333;
}
h1 {
font-size:2rem;
color:#fff;
}

Enter fullscreen mode Exit fullscreen mode

JavaScript Part

setInterval(showTime,1000);
function showTime(){
let date=new Date();
let time=date.toLocaleTimeString();
document.querySelector('.time').innerHTML=time;
}
Enter fullscreen mode Exit fullscreen mode

1000ms=1second

Creating a digital clock using setTimeout

HTML Part

<h1 class='clock'></h1>
Enter fullscreen mode Exit fullscreen mode

CSS Part

body {
font-family:'Poppins',sans-serif;
height:100vh;
background-color:#333;
display:flex;
justify-content:center;
align-items:center;
}
h1 {
font-size:2rem;
color:#fff;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript Part

let clock=document.querySelector('.clock');
function showTime(){
let date=new Date();
let h=date.getHours();
let m=date.getMiuntes();
let s=date.getSeconds();
let session='AM';
if(h===0){
h=12;
}
if(h>12){
h=h-12;
session='PM';
}
h=(h>10)?'0'+h:h;
m=(m>10)?'0'+m:m;
s=(s>10)?'0'+s:s;
let time=`${h} : ${m} : ${s} ${session}`;
clock.textContent=time;
setTimeout(showTime,1000);
}
showTime();
clock.addEventListener('load',showTime);
![chrome-capture](https://dev-to-uploads.s3.amazonaws.com/i/6lgcraigdjbmtdcen349.gif)

Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)