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

80
Vistas
I need to send event to the instance after fetching. Javascript Class

I want to call a function from a method. I don't even know how to ask correctly. test.onload() is called immediately, not after 3 seconds. See code for example, please.

export default class {
  constructor() {
    // some code
    setTimeout(() => {
      this.onload;
    }, 3000);
  }

  onload = (fn) => {
    console.log('loaded event');
    fn();
  };
}

const test = new TEST();

test.onload(function () {
  console.log('from instance');
});

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You are calling the function directly. Somehow you think that will be called when the setTimeout runs which is not the case.

If you want the function "from instance" to be called you need to rethink how you are registering it. You are going to have to store the function somehow and let the timer pick it up and execute it.

Setting it with the constructor

class TEST {
  constructor(callback) {
    this.callback = callback;
    setTimeout(() => this.onload(), 3000);
  }

  onload = () => {
    console.log('loaded event');
    if(this.callback) this.callback();
  };
}

const test = new TEST(function () {
  console.log('from instance');
});

Setting it with a method

class TEST {
  constructor() {
    setTimeout(() => this.onload(), 3000);
  }

  onload = () => {
    console.log('loaded event');
    if(this.callback) this.callback();
  };
  
  registerCallback(callback) {
    this.callback = callback;
  }
}

const test = new TEST();
test.registerCallback(function () {
  console.log('from instance');
});

about 4 years ago · Santiago Trujillo 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