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
  • 92,262
  • 30
  • 167
  • 149
David G
  • 94,763
  • 41
  • 167
  • 253

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
  • 133,157
  • 36
  • 148
  • 157
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,282
  • 5
  • 36
  • 53
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
  • 334,321
  • 69
  • 703
  • 674