Build a Simple Clock using JavaScript
Tags: javascript, beginners, webdev
Published: 2021-09-14 14:00:47

The best way to learn to code is by practice and building small projects. 
As part of this blog, let's build a simple clock that will print the local time of the user using JavaScript. This is great for beginners and for someone who has just started with JavaScript.

#### What will we learn as part of this blog?
1. Defining a function using function expression vs function declartion 
2. document.getElementById
3. setInterval
4. Element.innerHTML
5. Date.prototype.toLocaleDateString()

Let's get started!!!.

### Project structure
Create the list of files as listed below
1. index.html
2. script.js
3. style.css [ styles if we have any. As part of this blog, I am not going to add any styles as such.].

### HTML Structure - index.html
In the below HTML, 
- link the stylesheet inside the head tag
- link the javascript file inside the head tag
what will be present in those two files we will see later in the post. 

The next step is, inside the body tag add an element of your choice with an id attribute. I have added a paragraph as the element with the id value as a clock. This paragraph is where we are going to display our time.

```html
<!Doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Simple Clock using JavaScript</title>
        <link rel="stylesheet" href="styles.css">
        <script src="script.js"></script>
    </head>
    <body>
        <h1>Simple Clock - Current Time</h1>
        <p id="clock"></p>
    </body>
</html>
``` 

### Script - script.js
Let's break this down into steps
1. Create a function called clock and call the function.
2. Create a date object and retrieve the local time.
3. Call the function clock every second so that the clock gets updated with the new value.

#### 1. Create a function called clock and call the function.
This can be done in two ways using **function expression** or vs **function declaration**.  Read more about it  [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function) .
The main difference with function expression is they are not hoisted, you cannot call the function expression before they are declared.

In the below example, I have defined a function called clock which has console.log, and then I call the function at the end of the script. Save the script file and when you open the index.html. You should see "Hi" in the developer tool.

```javascript
//function expression
const clock = function() {
   console.log("Hi");
}
// or
//function declaration
function clock() {
  console.log("Hi");
}
clock();
```

#### 2. Create a date object and retrieve the local time.

> 
new Date()
When called as a constructor, returns a new Date object.

- toLocaleTimeString returns the current local time in a string format.
```javascript
const clock = function() {
    let getDate = new Date();
    console.log(getDate.toLocaleTimeString());
}
```
#### 3. Display the time inside the paragraph tag
- In the previous step we retrieved the value of the time, now we should display that value inside the paragraph tag.
- First, let's grab the element using its ID "clock"

> 
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.

- Into that element let's insert the time value returned by the date object. Using innerHTML we can set the value.

Now let's view this in the browser, what you should be seeing is, the current local time when the browser loaded for the first time. If you refresh the browser, you will see that it updates the time to the current minute. So every single time you want to see the current time, you will have to refresh the browser.

```javascript
const clock = function() {
    let getDate = new Date();
    document.getElementById('clock').innerHTML = getDate.toLocaleTimeString();
}
```
#### 4. Call the function using setInterval, for every few seconds.
With the last update, in order to see the current time, we had to refresh the browser every time so that the function gets called on refresh/page load and retrieves the current time. But a clock is supposed to update on its own, which means we will need the clock function to be executed every second to retrieve the current value. This is where we use the setInterval function.


> 
setInterval executes a function continuously for the given milliseconds.

Let's add the clock function inside the setInterval, now the clock function is repeated called for every 1000 seconds.

```javascript
const clock = function() {
    let getDate = new Date();
    document.getElementById('clock').innerHTML = getDate.toLocaleTimeString();
}
setInterval(function() { clock();}, 1000);
```

### Output


![Clock](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzs0v5ijivjteok81b4h.gif)

### References
-  [Function declaration vs Function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions) 
-  [date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString) 

Follow me on  [Twitter](https://twitter.com/KritikaPattalam)  | [LinkedIn](https://www.linkedin.com/in/kritika-p-296739155/) for more web development related tips and posts. Feedbacks and suggestions are welcome.