In this lesson we will learn how to create a Clock using Javascript. This is one of the most basic functions of javascript but learning how to optimize our code to make it presentable and easy for the User to understand (changing the clock from military time to standard time. Here is an example of what we will be creating.

javascript clock

The Set Up

Let’s start by creating our HTML. We don’t need much, just a <span> tag with an ID of “clock” will do.

Now we have the framework we need and somewhere to place our clock. Next we will write out and review our Javascript logic by using simple JS methods and altering the output to make it more like the clock we know and love today.

Javascript and HTML

Update your project with the following code:

As you can see, we had to do a little work around to get the clock the way we want. Let’s go over each comment and the logical steps we had to take:

  1. First we created a function called updateClock.
  2. We created some reusable variables with the methods used to retrieve the data.
  3. The minutes and seconds retrieved from Javascript will output as single integers if they are less than 10, we used a IF/Else to check and output the necessary 0 placeholders.
  4. Performed an If/Else statement to check the hours and if less than 12, output AM, if not output PM.
  5. Another If/Else statement that checks for any numbers above 12 and performs the proper math to display as 12-hour time instead of Military time.
  6. That last IF/Else statement that changes the 0 hour to the number 12.
  7. We create a variable called currentTimeString that displays the values of each statement put together.
  8. Created a function that calls the currentTimeString statement and places it in the element with the ID of “clock” (which would be in the <span>.
  9. In order for the clock to update and display the results every second, we tied a method to the <body> tag that set’s a check interval every 1000ms (or one second).

Adding Some Style

Since our clock has an ID, that means that we can target the text and style it with some CSS. If you’d like, use the css below to style the colors, size and font of your clock. We used an external font from Google Fonts and the provided link to spice up our font style. This should all be placed within the <head> tag.

Wrapping It Up

By using some simple javascript .get methods, we were able to retrieve the data and alter its presentation to resemble a more User friendly clock. A great idea to add-on to this project is to have clickable buttons that can retrieve different times from around the world. This can be done by either math or stepping up your coding experience by pulling server side code. Try it out.