0

While studying React, I came across following code block here:

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

Here, the first argument to setInterval is a function that returns tick() function. If I replace the 1st argument to setInterval with just this.tick, it does not work (meaning, clock stops ticking). Whereas it works with just passing the function here. Why is it so?

setInterval takes in a function. Why do we have to pass in an arrow-function that returns a function instead?

whitehat
  • 2,381
  • 8
  • 34
  • 47
  • More like calling context of `this`.... So did you write it as `setInterval( () => this.tick, 1000)` or `setInterval(this.tick, 1000)` – epascarello Oct 01 '18 at 20:42
  • 1
    You are *calling* a function with `this.tick()`. You will only return a function if `tick()` returns a function. – Mark Oct 01 '18 at 20:43
  • https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch – epascarello Oct 01 '18 at 20:45

2 Answers2

3

With an arrow function you ensure that the this value remains the same even if the function is executed in another context (like setInterval)

It is effectively the same as

this.timerID = setInterval(this.tick.bind(this), 1000);
  • Got it. So, if `binding` had not been required in React, or tick() had no use of `this` (to access the instance of this class), we might have as well used the function name directly. I checked by calling an external function directly from setInterval and it works. This helps. Thanks! – whitehat Oct 09 '18 at 04:23
1

The ()=>this.tick() is short hand for:

()=>{
  return this.tick()
}

When your lambda only has 1 line of code, you can leave out the brackets {...}

You're effectively returning the returned value of executing this.tick()

ACVM
  • 1,497
  • 8
  • 14
  • 1
    The other important thing to mention is that the `=>` syntax also preserves `this`, while `this.tick` alone would not. – Dark Falcon Oct 01 '18 at 20:47