JSFiddle - React, Tailwind, and code Playground

by Hari Menon

HTML

<div>
    <div> <span id="output"></span><span id="state"></span>

    </div>
    <div>
        <button id="start">Start</button>
        <button id="stop">Stop</button>
    </div>
</div>

CSS

#state {
    color: #ccc;
    font-size: smaller;
}

JavaScript

'use strict';

/*

401438723- Mon 2015-11-23
timer.start()
timer.stop() -> returns ms since start
timer.pause()

*/
/********/
var STOPPED = 'STOPPED',
    RUNNING = 'RUNNING',
    PAUSED = 'PAUSED';

function Timer(displayTimeCallback) {
    this.elapsedMilliSeconds = 0;
    this.startTime = 0;
    this.state = STOPPED;
    this._timer = null;
    this.displayTimeCallback = displayTimeCallback || function () {};
}
Timer.prototype.start = function () {
    if (this.state === RUNNING) {
        throw new Error("Timer is already running");
    }
    if (this.state !== PAUSED) {
        this.startTime = new Date();
    } else {
        this.startTime = new Date() - this.elapsedMilliSeconds;
    }
    this.state = RUNNING;
    var self = this;
    this._timer = setInterval(function () {
        self.displayTimeCallback(self.getElapsedMilliseconds());
    }, 1);
};
/**
 * returns time
 */
Timer.prototype.stop = function () {
    if (this.state !== RUNNING) {
        throw new Error('Timer shoukd be running');
    }
    var result = this.elapsedMilliSeconds;
    this.elapsedMilliSeconds = 0;
    this.state = STOPPED;
    clearInterval(this._timer);
    return result;
};
Timer.prototype.pause = function () {
    if (this.state !== RUNNING) {
        throw new Error('Timer shoukd be running');
    }
    this.elapsedMilliSeconds = this.getElapsedMilliseconds();
    this.state = PAUSED;
    clearInterval(this._timer);
};
Timer.prototype.getElapsedMilliseconds = function () {
    return new Date() - this.startTime;
};
/********/


function displayTimeCallback(time) {
    // console.log(time);
    document.getElementById('output').textContent = time / 1000;
}

function updateState() {
    document.getElementById('state').textContent = timer.state;
}
var timer = new Timer(displayTimeCallback);

document.getElementById('start').onclick = function () {
    if (timer.state === RUNNING) {
        timer.pause();
        document.getElementById('start').textContent = 'Resume';
   ...