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

前端 未结 6 436
-上瘾入骨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:31

    There are many ways to solve this problem, the following is my suggestion:

    function onloadFunctions() {
        var count = 0;
        var delta = 1;
        var target = document.getElementById("here");
        var step = function() {
            if(count <= 0) delta =  1;
            if(count >= 9) delta = -1;
            count += delta;
            target.innerHTML = count;
            window.setTimeout(step, 500);
        }
        step ();
    }
    

    PS: it's safer to use setTimeout than setInteval.

提交回复
热议问题