I just created a counter class that seems to work almost okay.
Unfortunately there is an issue that I cannot identify.
I instance my class twice with a different name but the parameters remain the same in terms of the chrono max limit.
Thanks to anyone who could help me…
I’m trying to create a class that can display a counter but there is a problem with the parameters. Of course I could just create a simple function instead but that’s not what I’m trying to do. I would like to stay in the same perspective if possible… Thanks to anyone who could help me…
I’ll let you look at the code a little further down.
document.addEventListener("DOMContentLoaded", (event) => {
console.log("DOM fully loaded and parsed");
});
class SuperCounter {
constructor(cumul, limit) {
this.cumul = cumul;
this.limit = limit;
}
add() {
if (this.cumul === this.limit) {
console.warn('Counter just reached to the limit');
clearInterval(ignition)
};
return {
result: this.cumul++,
//limit: this.limit,
}
}
}
const firstCounter = new SuperCounter(1, 50);
const secondCounter = new SuperCounter(1, 150);
const ignition = setInterval(displayCounter, 100);
function displayCounter() {
document.querySelector("#chrono1").innerHTML = /*html*/ `<h2>Chrono #1 : ${firstCounter.add().result}</h2>`
document.querySelector("#chrono2").innerHTML = /*html*/ `<h2>Chrono #2 : ${secondCounter.add().result}</h2>`
};
<h3 id="chrono1"></h3>
<h3 id="chrono2"></h3>
2
Answers
The main problem in your code is that you are calling
clearInterval()
from within yourSuperCounter.add()
method. What if aSuperCounter
object is being used independently of asetInterval()
?As you want to trigger the
add()
method of your counters in a synchronized way (in one commonsetInterval()
callback-function) and you want that function to be called repeatedly until both counters have reached their limits you should only callclearInterval(ignition)
after both counters are.done
. This property is set as soon as the limit of the counter has been reached.I also took the liberty of simplifying the return value of your
add()
method to the current counter value. And, in order to make the demo a little faster, I started the second counter at value 81 ;-).I wouldn’t use class syntax (why not?). Using
setTimeout
will give more control to the loop. Here is a demo counter factory function (replacing the class syntax) for some independent counters: