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

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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