2

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

2 Answers2

8

You'll need to use bind:

this.interval = setInterval(this.main.bind(this), 5000);
Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83
  • Can you give a few explanations? – GHopper Jul 28 '18 at 14:12
  • Thank, that worked. I'll study more about .bind because it is not yet clear why that works :) – Michele Tuloski Furci Jul 28 '18 at 14:13
  • Also read the [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) documentation. In your original code `this.main` was being called from global scope, so `this` was either the window object if you're running in a browser or the global object if you're running in node. – Andy Gaskell Jul 28 '18 at 14:19
0

You can try setInterval(() => this.main(), 5000) as well. this in JavaScript can differ than what you'd expect the program's source code to suggest. See MDN's take on this.

Horia Coman
  • 8,681
  • 2
  • 23
  • 25