How do I correctly use setInterval and clearInterval to switch between two different functions?

前端 未结 6 439
-上瘾入骨i
-上瘾入骨i 2020-12-01 12:53

For practice I am trying to display a number that increments from 0 - 9, then decrements from 9 - 0, and infinitely repeats.

The code that I have so far seems to

6条回答
  •  借酒劲吻你
    2020-12-01 13:14

    @Claude, you are right, the other solution I proposed was too different from original code. This is another possible solution, using setInterval and switching functions:

    function onloadFunctions() {
        var count = 0;
        var refId = null;
        var target = document.getElementById("aux");
    
        var countUp = function() {
            target.innerHTML = count;
            count ++;
            if(count >= 9) {
                window.clearInterval(refId);
                refId = window.setInterval(countDown, 500);
            }
        }
    
        var countDown = function() {
            target.innerHTML = count;
            count --;
            if(count <= 0) {
                window.clearInterval(refId);
                refId = window.setInterval(countUp, 500);
            }
        }
        refId = window.setInterval(countUp, 500);
    }
    

提交回复
热议问题