0

When we have a tick function

tick() {
    this.setState({
        date: new Date()
    });
}

why should we use something like,

componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
}

and not just simply

componentDidMount() {
    this.timerID = setInterval(this.tick, 1000);
}

I guess that we have some closure problem when I try the second variant. But can you please explain in detail what happens.

You can find the rest of the code here.

Script47
  • 14,230
  • 4
  • 45
  • 66
Igor Chernega
  • 611
  • 3
  • 7
  • 18
  • 3
    because of different `this`. Last version you can use with a little trick `this.tick.bind(this)` – MysterX Sep 04 '17 at 14:47

1 Answers1

4

Cause passing

setInterval(this.tick,1000)

behaves like:

 window.tick = this.tick;
setInterval(window.tick,1000);

So this inside tick is window, which hasnt a setState method.


Now the real answer:

In javascript the context ( aka this ) is determined when the function is called.

 a.b() // b called with context a
 c.d(); // d called with context c
 e();// e called with the default (window) context

So as the setInterval function looks like this ( actually its written in c, but thats another thing):

function setInterval(func, time, ...args){
  //await however
  func(...args);//context is window
}

you will always loose the context through setInterval. A workaround would be either .binding or using arrow functions, which always take their surrounding context ( so they have nothing to loose ;))

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151