Javascript
// Get this reference, just once outside of the function that it will be needed in
// instead of on each invocation of the function.
let clock = document.getElementById('clock');
let timer = null; // The timer variable is null until the clock initializes
// This is the modern way to set up events
clock.addEventListener("click", function(){
// If the clock is ticking, pause it. If not, start it
if(timer !== null){
clearInterval(timer); // Cancel the timer
timer = null; // Reset the timer because the clock is now not ticking.
} else {
timer = setInterval(runClock, 1000);
}
});
// Get a reference to the timer and start the clock
timer = setInterval(runClock, 1000);
function runClock() {
// .innerText is non-standard. Use .textContent instead.
// .toLocaleTimeString() gets you the locale format of the time.
clock.textContent = new Date().toLocaleTimeString();
}
// instead of on each invocation of the function.
let clock = document.getElementById('clock');
let timer = null; // The timer variable is null until the clock initializes
// This is the modern way to set up events
clock.addEventListener("click", function(){
// If the clock is ticking, pause it. If not, start it
if(timer !== null){
clearInterval(timer); // Cancel the timer
timer = null; // Reset the timer because the clock is now not ticking.
} else {
timer = setInterval(runClock, 1000);
}
});
// Get a reference to the timer and start the clock
timer = setInterval(runClock, 1000);
function runClock() {
// .innerText is non-standard. Use .textContent instead.
// .toLocaleTimeString() gets you the locale format of the time.
clock.textContent = new Date().toLocaleTimeString();
}
CSS
body { background: coral; }
#clock {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 3rem;
font-weight: bold;
color: #fff;
background: teal;
padding: 2rem;
border-radius: 5px 5px 5px 5px
}
#clock {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 3rem;
font-weight: bold;
color: #fff;
background: teal;
padding: 2rem;
border-radius: 5px 5px 5px 5px
}
HTML
<div id="clock"></div>
No comments:
Post a Comment