Welcome to a tutorial on how to create a simple Javascript clock. Need to add a clock to your website? Or just learning about timers in Javascript? Well, here’s a really simple example – Read on!
TABLE OF CONTENTS
JAVASCRIPT CLOCK
All right, let us now get into more details on how the Javascript clock works.
JAVASCRIPT CLOCK DEMO
PART 1) THE HTML
<div id="clockWrap"></div>
Yep, that’s all. A good old <div id="clockWrap">
container to show the clock.
PART 2) THE JAVASCRIPT
window.onload = () => {
// (A) GET HTML <DIV ID="CLOCKWRAP">
var hClock = document.getElementById("clockWrap");
// (B) HELPER FUNCTION TO PREPEND 0
var pzero = num => num<10 ? "0" + num : num ;
// (C) START TIMER
var timer = setInterval(() => {
let now = new Date();
hClock.innerHTML = `${pzero(now.getHours())} :
${pzero(now.getMinutes())} :
${pzero(now.getSeconds())}`;
}, 1000);
};
- Self-explanatory, get
<div id="clockWrap">
. pzero(num)
is a helper function to prepend a 0 tonum
if it is less than 10.var timer
is set to run every second.let now = new Date();
Get the current date/time.hClock.innerHTML = ...
Reformat the current time, and set it into<div id="clockWrap">
.
Read up on Javascript ternary operator and arrow functions if you are lost. Arrow functions are the “shorthand way to define functions”, and ternary is the “shorthand way to define if-else”. Basically:
var pzero = function (num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
PART 3) THE CSS
#clockWrap {
/* (A) FONT */
font-family: Arial, sans-serif;
font-size: 40px;
/* (B) CENTER */
text-align: center;
}
I don’t think this even needs an explanation… Literally just setting the font, font size, and centering the text.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
EXTRA) HOW ABOUT ADDING THE DATE?
It should not be too difficult once you have figured out the majority of the above. I shall leave this as “homework” with some hints:
now.getFullYear()
now.getMonth()
now.getDate()
now.getDay()
LINKS & REFERENCES
- Set Interval – MDN
- Arrow Functions – MDN
- Date – MDN
- Example on CodePen – Simple Javascript Clock
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!