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

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

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 Report

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