Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
How do I keep track of multiple objects in Javascript

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();
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Lose the dots before array brackets: globalThis.timers.[id].starter() should be globalThis.timers[id].starter()

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should accept aPajos answer as it pointed out your actual error. As for the "more correct way", get rid of inline javascript

var timers = {};

/*Get the buttons with the data attributes*/
let timerButtons = document.querySelectorAll("button[data-timerid]");
/*Itterate them adding an event handler*/
timerButtons.forEach(function(item){
  item.addEventListener("click", function(){
    /*Get the id from the data atttribute*/
    let timerId = this.dataset.timerid;
    /*Better to go the positive case first*/
    if(timers[timerId]){
      timers[timerId].resetIt();
    }else{
      timers[timerId] = new CUTimer(timerId);
    }
  });
})


function CUTimer(id){
  this.id = id;
  this.starter = function(){console.log("Starting : " + this.id)};
  this.resetIt = function(){console.log("Resetting : " + this.id)};
  //Call your starter method in the construtor
  this.starter();
};
<!-- Use Data Attributes to store the timer Id -->
<button type="button" data-timerid='KT1'>Timer 1</button>
<button type="button" data-timerid='KT2'>Timer 2</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda