Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS class method in a setInterval doesn't work [duplicate]

I have this simple example with a class with a setInterval that calls main() every 5 seconds. When it comes to call print() it returns me TypeError: this.print is not a function. And I'm really stuck. Why if I call main() without setInterval it works smoothly but with setInterval it fails? It's weird. Any workaround to call main() periodically without this issue?

"use strict";

class test {
  constructor() {
      this.interval = setInterval(this.main, 5000);
  }

  print(){
      console.log('Teeeessssttt');
  }

  main(){
      this.print();
  }
}

const a = new test();
like image 273
Michele Tuloski Furci Avatar asked Feb 13 '26 03:02

Michele Tuloski Furci


1 Answers

You'll need to use bind:

this.interval = setInterval(this.main.bind(this), 5000);
like image 79
Andy Gaskell Avatar answered Feb 15 '26 17:02

Andy Gaskell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!