Clock Example -- Source Code

HTML Page -- index.htm

 <!DOCTYPE html>

<!-- Clock Example 
     Source Code File: index.htm -->

<html lang="en">
    <head>
        <title>Clock Example</title>
        <script src="clock.js"></script>
        <script src="script.js"></script>
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>
        <h2>Clock Example</h2>
        <p id="time"></p>
    </body>
</html>

CSS Page -- styles.css

 /* Clock Example
   Source Code File: styles.css */

body { font-size: 200%;
color: navy; 
background-color: #E0E0FF; }

h2, p { font-family: verdana; }

Script File -- clock.js

 // Clock Class
class Clock {
    constructor(hr, min, sec) {
        this.hr = hr;
        this.min = min;
        this.sec = sec;
    }

    tick( ) {
        this.sec++;
        if(this.sec == 60) {
        this.sec = 0;
            this.min++;
        }
        if(this.min == 60) {
            this.min = 0;
            this.hr++;
        }
        if(this.hr == 24) {
            this.hr = 0;
        }
    }

    toString( ) {
        var h = this.hr.toString( ).padStart(2, "0");
        var m = this.min.toString( ).padStart(2, "0");
        var s = this.sec.toString( ).padStart(2, "0");
        return `${h}:${m}:${s}`;
    }
}

Script File -- script.js

 // Clock Example
// Source Code File: script.js

window.clock = new Clock(20, 45, 0);

function handleTick( ) {
    var para = document.getElementById("time");
    window.clock.tick( );
    para.innerHTML = window.clock.toString( );
}

function init( ) {
    // Call the handleTick method every
    // 1000 milliseconds (every second).
    window.setInterval(handleTick, 1000);
}
window.addEventListener("load", init);