I’m building a simple digital clock on JavaScript and have implemented the 12 hour format clock as follows:
function get12hrTime()
{
var date=new Date();
var hh=date.getHours();
var mm=date.getMinutes();
var ss=date.getSeconds();
var session="AM";
if(hh==0)
{
hh=12;
}
if(hh>12)
{
hh=hh-12;
session = "PM";
}
hh=(hh<10)? "0" + hh : hh;
mm=(mm<10)? "0" + mm : mm;
ss=(ss<10)? "0" + ss : ss;
let time = hh + "." + mm + "." + ss + " "+session;
document.getElementById("time").innerHTML = time;
let t1=setTimeout(function(){
get12hrTime()
},1000);
}
I’m calling this via an onclick function. Now I’m trying to implement a format switcher for 24hr format as :
function get24hrTime()
{
var date=new Date();
var hh=date.getHours();
var mm=date.getMinutes();
var ss=date.getSeconds();
var session="AM";
if(hh>12)
{
session = "PM";
}
hh=(hh<10)? "0" + hh : hh;
mm=(mm<10)? "0" + mm : mm;
ss=(ss<10)? "0" + ss : ss;
let time = hh + "." + mm + "." + ss + " "+session;
document.getElementById("time").innerHTML = time;
let t2=setTimeout(function(){
get24hrTime()
},1000);
}
The issue is that the timeouts are not syncing and if I use the switcher after I get the 12hr time the time keeps switching between 12hr and 24hr.
I tried using clearTimeout but couldnt find a way to do so. I could always use 2 buttons for 12hr and 24hr but I want a switcher. Is there a way to stop the timeout in the other function in the 24hr function?
2
Answers
If the
t1
andt2
variables are in a higher scope, both functions can access them and clear them. For example:This way each "clock" always clears any existing timeout for the other "clock" before setting its own.
You need to move
t1
andt2
to the higher scopeI also removed from duplicates from your code: