简体   繁体   English

具有定时事件(setTimeout)的JavaScript递归

[英]JavaScript Recursion with Timing Event (setTimeout)

I am trying to build a timer with JavaScript. 我正在尝试使用JavaScript构建计时器。 Here's my function: 这是我的功能:

var t;
function time(num){
    var buf = num;
    document.getElementById("test").innerHTML=buf;
    buf++;
    alert(buf + " " + num); //For troubleshooting
    t=setTimeout("time(buf)",1000);
}

If I run time(0), nothing happens to the part with ID="test". 如果我运行time(0),则ID =“ test”的部件将什么也没有发生。 num always equals 0 and buf always equals 1 (from the alert function) every time the function is called. 每次调用该函数时, num始终等于0,而buf始终等于1(来自alert函数)。

I'm comfortable with Java and C, and I know this would work in those language. 我对Java和C感到很满意,并且我知道这会在那些语言中起作用。 I know JavaScript is also a pass-by-value language, so why doesn't this timer work? 我知道JavaScript也是一种传递值的语言,那么为什么此计时器不起作用?

Also, why did nothing happen when I tried (and changed all the buf to num ) 另外,为什么当我尝试时什么都没发生(并将所有buf更改为num

t=setTimeout("time(num)",1000);

I know there are other ways to create a timer, but I want to know why this method doesn't work. 我知道还有其他创建计时器的方法,但是我想知道为什么此方法不起作用。 Thanks. 谢谢。

Avoid passing strings to setTimeout . 避免将字符串传递给setTimeout When you do this the string is more or less executed as an eval , which is evil for many reasons. 当您执行此操作时,该字符串或多或少被作为eval执行,由于许多原因,这是邪恶的。 See this question for more information. 有关更多信息,请参见此问题

Instead, consider passing an anonymous function to setTimeout . 相反,请考虑将匿名函数传递给setTimeout This will make solving your problem trivial: 这将使您解决问题变得微不足道:

t = setTimeout(function() { time(buf); }, 1000);

When you pass a string to setTimeout , it is evaluated when the time comes. 将字符串传递给setTimeout ,将在时间到来时对其进行评估。 In this case, when the time comes, there's no buf variable anymore and the code throws an error. 在这种情况下,当时间到了时,就不再有buf变量,并且代码将引发错误。

You should substitute the value yourself. 您应该自己替换值。

t = setTimeout("time(" + buf + ")",1000);

Or, better yet, pass a function instead of string 或者,更好的是,传递一个函数而不是字符串

t = setTimeout(function() {
  time(buf);
}, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM