setInterval中的Javascript函数 [英] Javascript function in setInterval

查看:99
本文介绍了setInterval中的Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我有以下代码:

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

哪些工作正常。



如果将其更改为:

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

它只在控制台中执行一次而没有错误。
有人可以解释为什么当我在 setInterval 函数中包含 los 之后的情况时会发生这种情况吗?



预先感谢您!
新年快乐!

解决方案

请记住,在JavaScript中,函数是一个对象,像任何其他对象一样传递变量。所以这是对函数的引用:

  los 

另一方面,执行函数并计算其结果:

 los()

所以当你这样做时: p>

  setInterval(los(),1000)

您没有设置函数的间隔,而是设置函数的结果。所以,例如,如果函数返回 true ,那么你基本上是这样写的:

  setInterval(true,1000)

函数执行一次,然后间隔重复为其结果。你想要的是在间隔中使用函数引用本身:

pre $ set $($,$ 1000 $)

code>

那样 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆