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");
}
3
  • 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... Commented Jul 25, 2016 at 2:04
  • This question has been asked a hundred times. Please search harder. You could off by reading up on how this works. Commented Jul 25, 2016 at 2:17
  • See also stackoverflow.com/questions/37802436/…. Commented Jul 25, 2016 at 2:19

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

5 Comments

setInterval doesn't take anything out of context. The context is lost the minute you say this.repeat.
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
I cannot parse your comment. Nothing is being "re-assigned". The value this.repeat has no context to start with.
@DayanMorenoLeon—you can not "reassign the functions execution context", you have absolutely no control over that. Perhaps you just misused execution context. ;-)
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 medium.com/dailyjs/… bennadel.com/blog/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.