Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am learning about react components following the documentation https://facebook.github.io/react/docs/state-and-lifecycle.html

Why do we need to use arrow function here:

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

Why can't I just say (obviously it doesn't work)

this.timerID = setInterval(this.tick(), 1000);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
267 views
Welcome To Ask or Share your Answers For Others

1 Answer

The first argument for setInterval is of type function. If you write this:

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

…then you don't pass a function, instead you execute the function this.tick immediately and then pass the value returned by that function call as an argument.

You could write it like this:

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

If you omit the parentheses, you pass a reference to your this.tick function, which is then executed by setInterval after 1000 milliseconds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...