JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

New Interval Time: <input id="timer" value="1"><br>
<button id="reset">Reset</button>
<button id="stop">Stop</button>
<button id="start">Start</button>
<hr>
<div id="logger"></div>

CSS

input {
    margin-bottom: 10px;
}

JavaScript

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new interval, stop current interval
    this.reset = function(newT) {
        t = newT;
        return this.stop().start();
    }
}

function logTop(msg) {
    var target = document.getElementById("logger");
    var div = document.createElement("div");
    div.innerHTML = msg;
    target.insertBefore(div, target.firstChild);
}

var cntr = 1;
var startTime = Date.now();
var timer = new Timer(function() {
    logTop(cntr++ + ": " + ((Date.now() - startTime) /1000).toFixed(3));
}, 1000);

document.getElementById("reset").addEventListener("click", function(e) {
    var newTime = +document.getElementById("timer").value * 1000;
    if (newTime) {
        timer.reset(newTime);
    }
});

document.getElementById("start").addEventListener("click", function(e) {
	  timer.start();
});

document.getElementById("stop").addEventListener("click", function(e) {
    timer.stop();
});