简体   繁体   中英

JavaScript Recursion with Timing Event (setTimeout)

I am trying to build a timer with 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". num always equals 0 and buf always equals 1 (from the alert function) every time the function is called.

I'm comfortable with Java and C, and I know this would work in those language. I know JavaScript is also a pass-by-value language, so why doesn't this timer work?

Also, why did nothing happen when I tried (and changed all the buf to 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 . When you do this the string is more or less executed as an eval , which is evil for many reasons. See this question for more information.

Instead, consider passing an anonymous function to 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. In this case, when the time comes, there's no buf variable anymore and the code throws an error.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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