JSFiddle - React, Tailwind, and code Playground
HTML
Counter Time (this will increment count1 and print both counts):<br>
<input id="text" value="5000">
<button id="button">
Change
</button>
<br>Counter2 Time (this will increment count2):<br>
<input id="text2" value="1000">
<button id="button2">
Change
</button>
<br>
JavaScript
function VariableTimer(cb, iv) {
return {
running: false,
iv: iv,
timeout: false,
cb: cb,
start: function(cb, iv) {
var elm = this;
clearInterval(this.timeout);
this.running = true;
if (cb) this.cb = cb;
if (iv) this.iv = iv;
this.timeout = setTimeout(function() {
elm.execute(elm)
}, this.iv);
return this;
},
execute: function(e) {
if (!e.running) return false;
e.cb();
e.start();
},
stop: function() {
this.running = false;
},
set_interval: function(iv) {
clearInterval(this.timeout);
this.start(false, iv);
}
};
}
var count1 = 0;
var count2 = 0;
//intitiate 1 counter
var counter1 = VariableTimer( function() {
console.log("Count1:" + count1++ + "; Count2:" + count2);
}, $("#text").val()).start()
//initiate 2nd counter
var counter2 = VariableTimer( function() {
count2++;
}, $("#text2").val()).start();
//change the intervals
$("#button").click( function() {
counter1.set_interval($("#text").val());
});
$("#button2").click( function() {
counter2.set_interval($("#text2").val());
});