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

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

    clearInterval(this);. You can't do that. You need to save the return value from setInterval.

    var interval;
    function onloadFunctions()
    {
        countUp();
        interval = setInterval(countUp, 200);
    }
    
    var count = 0;
    function countUp()
    {
        document.getElementById("here").innerHTML = count;
        count++;
    
        if(count == 10)
        {
            clearInterval(interval);
            countDown();
            interval = setInterval(countDown, 200);
        }
    }
    function countDown()
    {
        document.getElementById("here").innerHTML = count;
        count--;
    
        if(count == 0)
        {
            clearInterval(interval);
            countUp();
            interval = setInterval(countUp, 200);
        }       
    }
    

提交回复
热议问题