Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!