How To Make Simple Stopwatch Using Plain Javascript?

In the plain javascript you can use factory function or construction function to create an object.

Let's create a stop watch example to show how to a create a construction function. It has three methods start, stop and reset and private variables are defined as startTime, endTime, running and duration. Also it is defined readonly property called duration using Object.defineProperty method. this keyword is being used to set the properties of an object Stopwatch.
function Stopwatch() {
    let startTime = null;
    let endTime = null;
    let running = false;
    let duration = 0;

    this.start = function() {
        if (running) {
            throw new Error('Stopwatch has already started.');
        }

        running = true;

        startTime = new Date();
    };

    this.stop = function() {
        if (!running) {
            throw new Error('Stopwatch is not started yet.');
        }

        running = true;

        endTime = new Date();

        const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
        duration += seconds;

    };

    this.reset = function() {
        startTime = null;
        endTime = null;
        running = false;
        duration = 0;
    };

    //readonly property
    Object.defineProperty(this, 'duration', {
        get: function() {
            return duration;
        }
    });

}
In your browser's console log, you can run this example as below
const sw = new Stopwatch();

sw.start()
sw.stop()
sw.duration
sw.reset()

Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh | Stop watch Exercise

Comments

Popular Posts