How to create digital clock in Vanilla JS
ahmadullah
Posted on February 13, 2021
I can create a digital clock in two ways the first one is using setInterval method.
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>
CSS Part
body {
display:flex;
align-items:center;
justify-content:center;
height:100vh;
background-color:#333;
}
h1 {
font-size:2rem;
color:#fff;
}
JavaScript Part
setInterval(showTime,1000);
function showTime(){
let date=new Date();
let time=date.toLocaleTimeString();
document.querySelector('.time').innerHTML=time;
}
1000ms=1second
Creating a digital clock using setTimeout
HTML Part
<h1 class='clock'></h1>
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;
}
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)
💖 💪 🙅 🚩
ahmadullah
Posted on February 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Understanding HTTP, Cookies, Email Protocols, and DNS: A Guide to Key Internet Technologies
November 30, 2024