setInterval function without arrow function

点点圈 提交于 2019-11-29 18:54:01

问题


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);

回答1:


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.




回答2:


setInterval takes function as first argument, in the second case it is getting a returned value

Change it to

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

or

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

which is probably what you need when you want to bind the function to the React context.

See this answer on why you need to bind functions in React

If you don't you could have simply written

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



回答3:


You need to supply a function reference, you are trying to invoke a function, unless that function returns a function reference, your code will not work

It should look like so

this.tick = function() { .... }

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



回答4:


If you are not using arrow function then your code should look something like this:

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



回答5:


Technically, you should be able to use the second code snippet if this.tick() returns a function.



来源:https://stackoverflow.com/questions/45780551/setinterval-function-without-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!