I am building a page with multiple timers on it. The timers are created when a user clicks a button. So let's say user clicks "K Timer 1" button. The JS created a new timer I want to reference as "KT1" or timers['KT1'].
Here is the way I am trying to do it and you JS peeps are probably laughing at my solution right now. That's OK. I am much more at home with PHP.
HTML
<button type="button"
onClick="newUTimer('KT1');">
Timer 1
</button>
<button type="button"
onClick="newUTimer('KT2');">
Timer 2
</button>
JS - Old with errors
var timers = {};
newUTimer=function(id){
// If timer does not exist, create it
if (!globalThis.timers.[id]){
globalThis.timers.[id] = new CUTimer(id);
globalThis.timers.[id].starter();
// If there is already a timer with that ID, reset it
}else{
globalThis.timers.[id].reset();
}
}
The reason I need to keep track of the timers is so that I can reset the timer when a user click button for the second time instead of creating another conflicting timer.
JS - UPDATED and Working but not sure this is the correct way I should do this.
var timers = {};
newUTimer=function(id){
// If timer does not exist, create it
if (!globalThis.timers[id]){
globalThis.timers[id] = new CUTimer(id);
globalThis.timers[id].starter();
// If there is already a timer with that ID, reset it
}else{
// Call object resetIt method
globalThis.timers[id].resetIt();
}
}