3

I'm having issues with the window.setInterval() method. Below is an example of the structure, the method "repeat" is called repeatedly, however I cannot call any methods inside "repeat". In the example when I instantiate manager (let m = new manager()) it will print "Before Print", but will not print out the log from the printStuff method, or the "After Print" message.

Does anyone know why this is happening? Obviously this isn't my actual code as it's simple enough to not be in separate functions, however my actual code needs to call many functions in the "repeat" function and it will stop execution when it finds a call to another function.

class manager{

constructor(){
    window.setInterval(this.repeat, 5000);
}

repeat(){
    console.log("Before Print");
    this.printStuff();
    console.log("After Print");
}

printStuff(){
    console.log("Print Stuff");
}
annedroiid
  • 6,267
  • 11
  • 31
  • 54
  • Try `setInterval(this.repeat.bind(this), 5000)` - Did you check the console for error messages? I'd expect something about `printStuff` being undefined, because the way you have it `this` isn't what you think it is... – nnnnnn Jul 25 '16 at 02:04
  • This question has been asked a hundred times. Please search harder. You could off by reading up on how `this` works. –  Jul 25 '16 at 02:17
  • See also http://stackoverflow.com/questions/37802436/why-does-method-on-object-loose-correct-this-binding-in-settimeout. –  Jul 25 '16 at 02:19

1 Answers1

11

Set interval will take take the this.repeat out of the context you need to either explicitly 'bind' the method using

setInterval(this.repeat.bind(this), 5000)

or

setInterval(()=>this.repeat(), 5000)

Dayan Moreno Leon
  • 5,357
  • 2
  • 22
  • 24
  • `setInterval` doesn't take anything out of context. The context is lost the minute you say `this.repeat`. –  Jul 25 '16 at 02:17
  • not true the times, all of them, reassign the functions execution context thats why this does no mean the same unless you explicitly bind the functions – Dayan Moreno Leon Jul 25 '16 at 02:53
  • I cannot parse your comment. Nothing is being "re-assigned". The value `this.repeat` has no context to start with. –  Jul 25 '16 at 04:38
  • @DayanMorenoLeon—you can not "*reassign the functions execution context*", you have absolutely no control over that. Perhaps you just misused [*execution context*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-execution-contexts). ;-) – RobG May 31 '17 at 06:25
  • when you bind a function you are reassigning the context (this) in which is executed you can use implicit binding or explicit binding using bind, call or apply, a few readings about it https://medium.com/dailyjs/javascript-basics-the-execution-context-and-the-lexical-environment-3505d4fe1be2 https://www.bennadel.com/blog/2265-changing-the-execution-context-of-javascript-functions-using-call-and-apply.htm – Dayan Moreno Leon May 31 '17 at 07:19