Javascript function in setInterval

喜夏-厌秋 提交于 2019-11-28 10:30:20

问题


I have the following code:

var foo=5;
var los= function (){
    alert(foo);};
setInterval(los, 1000);

which works correctly.

If I change it to :

var los= function (){
    alert(foo);};
setInterval(los(), 1000);

it only executes once with no errors in console. Can someone explain me why this happens when I include the parentesis after los in the setInterval function?


回答1:


Keep in mind that in JavaScript a function is an object, passed around like any other variable. So this is a reference to the function:

los

This, on the other hand, executes the function and evaluates to its result:

los()

So when you do this:

setInterval(los(), 1000)

You're not setting the interval to the function, but to the result of the function. So, for example, if the function returns true then you're essentially writing this:

setInterval(true, 1000)

The function executed once, then the interval is repeated for its result. What you want is to use the function reference itself in the interval:

setInterval(los, 1000)

That way setInterval will execute the function each interval, instead of executing its result (which doesn't do anything).




回答2:


Because you're executing los() and then the result of that (single) execution is passed into the setInterval function.

setInterval requires a function passed in, not undefined, which is what los returns. However, it doesn't complain - it just doesn't do anything.




回答3:


The () you've got in the second one means to call the function before passing the result to setInterval. The parentheses are the operator that explicitly request that a function be called; that's why you put the parentheses around the arguments to setInterval, after all.

The name of a function, by itself, is a valid expression in JavaScript. The value of such an expression is a reference to the function. That's the value that you want when you're setting up an interval timer — you want to tell the system what function to call when the timer expires, so you pass a reference to it.



来源:https://stackoverflow.com/questions/20885236/javascript-function-in-setinterval

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