Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
Avoiding creating additional variables for the object with this and methods inside the object

I have created a timer object with different timer methods, and I am fully happy how it works. However, I am unhappy with the code quality. I cannot understand how I can get the same working methods without creating additional variables, in particular the property intervalId and the function resetSecAddMin. Is it possible to have this solution working without these additional variables?

The code:

const timer = {
  secondsPassed: 0,
  minsPassed: 0,
  intervalId: null,
  startTimer() {
    this.intervalId = setInterval(() => {
      const resetSecAddMin = () => { this.secondsPassed = 0; this.minsPassed += 1 };
      this.secondsPassed < 59 ? this.secondsPassed += 1 : resetSecAddMin();
      }, [1000]);
  },
  getTime() {
    return this.secondsPassed < 10 ? `${this.minsPassed}:0${this.secondsPassed}` : `${this.minsPassed}:${this.secondsPassed}`;
  },
  stopTimer() {
    clearInterval(this.intervalId);
  },
  resetTimer() {
    this.secondsPassed = 0;
    this.minsPassed = 0;
  },
};

I hope this question will contribute some value to the community. I believe that writing a readable code is not less important than creating working solutions.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You actually don't need any timer. On startTimer() method you record start time this.startTime = Date.now(). And then inside getTime() you get the delta in milliseconds var delta = Date.now() - this.startTime. It will be in milliseconds, but you can divide by 1000 to get seconds and figure out minutes too by division.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda