1
(function() {
    var count = {
        digit: 0,
        increment: function() {
            var interval = setInterval(function() {
                if (++count.digit == 10) {
                    clearInterval(interval);
                    count.decrement();
                }
                var update = document.getElementById("liveUpdate");
                update.innerHTML = count.digit;
            }, 500);
        },
        decrement: function() {
            var interval = setInterval(function() {
                if (--count.digit == -1) {
                    clearInterval(interval);
                }
            }, 500);
        }
    };
    count.increment();
})();

It stops but it doesn't go down? What could be the problem?

David Tang
  • 89,706
  • 29
  • 164
  • 149
David G
  • 90,891
  • 40
  • 158
  • 247

3 Answers3

4

Your decrement function never updates the output anywhere. The variable is going down but you don't show that on screen.

Try (or check the corresponding JSFiddle):

(function() {
    var update = document.getElementById("liveUpdate");
    var count = {
        digit: 0,
        increment: function() {
            var interval = setInterval(function() {
                if (++count.digit == 10) {
                    clearInterval(interval);
                    count.decrement();
                }
                update.innerHTML = count.digit;
            }, 500);
        },
        decrement: function() {
            var interval = setInterval(function() {
                if (--count.digit == -1) {
                    clearInterval(interval);
                }
                update.innerHTML = count.digit;
            }, 500);
        }
    };
    count.increment();
})();
Gareth
  • 124,675
  • 36
  • 145
  • 155
2

setInterval will call the function every 500 seconds. It will not stop until you stop it. You can read more about stopping it at Stop setInterval call in JavaScript

Community
  • 1
  • 1
Peeter
  • 9,072
  • 4
  • 35
  • 52
2

It't not a bug, it's a feature ;-). setInterval() runs the given function in a loop with a given interval (500 ms). See this article for details.

Tomasz Nurkiewicz
  • 324,247
  • 67
  • 682
  • 662