Javascript function in setInterval

后端 未结 3 1480
悲&欢浪女
悲&欢浪女 2020-12-22 04:07

I have the following code:

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

which works correctly.

If I

相关标签:
3条回答
  • 2020-12-22 04:27

    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.

    0 讨论(0)
  • 2020-12-22 04:41

    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.

    0 讨论(0)
  • 2020-12-22 04:49

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

    0 讨论(0)
提交回复
热议问题