JSFiddle - React, Tailwind, and code Playground

JavaScript

class Interval {

    constructor(interval, onTick) {
        this.interval = interval;
        this.onTick = onTick || function() {};
        this.timer = false;
        this.ticks = 0;
        this.startTime = 0;
        this.currentTime = 0;
        this.elapsedTime = 0;
        return this;
    }

    run() {
        this.currentTime = Date.now();
        if (!this.startTime) {
            this.startTime = this.currentTime;
        }

        this.onTick();

        let nextTick = this.interval - (this.currentTime - (this.startTime + (this.ticks * this.interval)));
        console.log(nextTick);
        this.ticks++;

        let self = this;
        this.timer = setTimeout(function() {
            self.run();
        }, nextTick);

        return this;
    }

    start() {
        this.run();
        return this;
    }

    stop() {
        clearTimeout(this.timer);
        return this;
    }
}


//new Interval(1000, function(){console.log()}).start();
//new Interval(100, function(){console.log()}).start();
//new Interval(10, function(){console.log()}).start();
//new Interval(1, function(){console.log()}).start();