开发者

Incrementing a number with JavaScript returns an error

var count = {
    digit: 0,
    increment: function() {
        setInterval(function() {
            count.digit++;
        }, 500);
        if (count == 10) {
      开发者_如何学运维      count.increment = null;
        }
    }
};
document.write("The number is " + count.digit);
count.increment();

The result is: "The number is 0" but it does not increment. Why?


"A string" + "another string" == "A new string"

… and a new string is not a live updating version of the combination of the two strings that formed it in the first place.

Even if it was, then document.write takes a string, expresses it as HTML, then adds it to the document — so that wouldn't live update it either.

You would need to use DOM methods to modify the HTML document instead of the string. The WSC has a good introduction to manipulating HTML with DOM: http://dev.opera.com/articles/view/creating-and-modifying-html/

You have another problem in that setting count.interval to null wouldn't stop the function incrementing the counter every half second since:

  1. You aren't overwriting the function that is being called every half second
  2. Replacing a reference to a function with something else, doesn't stop that function from existing unless all references to it are overwritten, and setInterval would maintain the reference.

You need to keep the return value from setInterval and use it to clearInterval.


You need to have your if statement inside the setInterval also count.digit == 0

This is a bit cleaner IMO

var count = {
    digit: 0,
    increment: function() {
        var interval = setInterval(function() {
            if (++count.digit == 10)
                clearInterval(interval);
            document.write("The number is " + count.digit);
        }, 500);
    }
};
count.increment();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜