TImer Display HTML & Vanilla JS

Post Reply
admin
Site Admin
Posts: 31
Joined: Mon Sep 16, 2024 5:00 pm
Contact:

TImer Display HTML & Vanilla JS

Post: # 286Post admin »

Code: Select all

<html>
  <head>
  </head>
  <body>
<div id="timerBlock" style="z-index:10000;position:fixed; bottom:0;right:0;background-color:#c0c0c0;color:#000000;border:1px solid #000000;height:20px;width:55px;font-family:Arial;font-size:12px;text-align:right;padding:0px;padding-top:5px;margin:5px;">
00:00:00&nbsp;</div>

<script>
let seconds = 0;
let minutes = 0;
let intervalId;

function secondsToHms(totalSeconds) {
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  const hDisplay = zPad(hours); // > 0 ? hours + (hours === 1 ? " hour, " : " hours, ") : "";
  const mDisplay = zPad(minutes); // > 0 ? minutes + (minutes === 1 ? " minute, " : " minutes, ") : "";
  const sDisplay = zPad(seconds); // > 0 ? seconds + (seconds === 1 ? " second" : " seconds") : "";

  return hDisplay + ":" + mDisplay + ":" + sDisplay;
}


function startCounter() {
  intervalId = setInterval(() => {
    seconds++;
    timerBlock.innerHTML = secondsToHms(seconds) + "&nbsp;"; //console.log(seconds);
  }, 1000);
}

function stopCounter() {
  clearInterval(intervalId);
}

// Start the counter
startCounter();

function zPad(pNum) {
 pNumSTR = "0" + pNum;
 return(pNumSTR.substr(pNumSTR.length-2));
}


// Stop the counter after 10 seconds (for example)

//setTimeout(stopCounter, 10000);
</script>

 </body>
</html>
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest