setInterval中的Javascript函数 [英] Javascript function in setInterval
问题描述
大家好我有以下代码:
var foo = 5;
var los = function(){
alert(foo);};
setInterval(los,1000);
哪些工作正常。
如果将其更改为:
var los = function( ){
alert(foo);};
setInterval(los(),1000);
它只在控制台中执行一次而没有错误。
有人可以解释为什么当我在 setInterval
函数中包含
预先感谢您!
新年快乐!
请记住,在JavaScript中,函数是一个对象,像任何其他对象一样传递变量。所以这是对函数的引用:
los
另一方面,执行函数并计算其结果:
los()
所以当你这样做时: p>
setInterval(los(),1000)
您没有设置函数的间隔,而是设置函数的结果。所以,例如,如果函数返回 true
,那么你基本上是这样写的:
setInterval(true,1000)
函数执行一次,然后间隔重复为其结果。你想要的是在间隔中使用函数引用本身:
pre $ set $($,$ 1000 $)
那样 setInterval
会执行每个间隔的函数,而不是执行它的结果(它什么也不做)。
Hello everyone 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?
Thank you in advance! Happy new year!
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).
这篇关于setInterval中的Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!