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

186
Visualizações
Weirdly javascript setInterval executes only once in this case with this class

I'm doing some experiments with class and weirdly in this special case, setInterval is only called once if I pass test.method1() and I get error if I pass test.method1, why ?

class Test {

  constructor() {
    this.counter = 0;
    (async () => {
      this.test();
    }
    )();
  }

  test() {
    this.method1();
  }
  method1() {
    let value;
    value = this.method2();
    console.log(this.counter);

  }
  method2() {
    this.counter++;
    return this.counter;
  }
}

let test = new Test();
let id = setInterval(test.method1(), 1000);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I get error if I pass test.method1, why ?

Because this context is lost. If you console.log(this) inside method1, you will not get an instance of Test. Basically, it's

const orphanedMethod = test.method1; // I'm not bound to the test variable now...
setInterval(orphanedMethod, 1000); // and if I try to access `this`, I'll get Window or sth like that

Either make method1 an arrow function:

method1 = () => {
    let value;
    value = this.method2();
    console.log(this.counter);
}

or explicitly bind it to the object when calling:

setInterval(test.method1.bind(test), 1000);
about 4 years ago · Juan Pablo Isaza Relatório

0

your error is JS cannot find method1 method inside test method because method1 is only called inside your test method. To do test.method1(), you should put your method1 definition inside your test method.

another thing is setInterval simply did not work, probably because you stored it in a variable and did not call id(). It only worked once because you explicitly called test.method1() inside your setInterval

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