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