如何正确使用setInterval和clearInterval在两个不同的函数之间切换?

Ian*_*ell 15 javascript animation counter setinterval clearinterval

为了练习,我试图显示一个从0 - 9递增,然后从9 - 0递减,并无限重复的数字.

我迄今似乎代码接近,但在第二次迭代中setInterval的我2个各自函数的调用countUp,并countDown似乎彼此发生冲突,因为显示的数字没有在预期的顺序计数......然后浏览器崩溃.

这是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Algorithm Test</title>
    </head>

    <body onload = "onloadFunctions();">
        <script type = "text/javascript">
            function onloadFunctions()
            {
                countUp();
                setInterval(countUp, 200);
            }

            var count = 0;
            function countUp()
            {
                document.getElementById("here").innerHTML = count;
                count++;

                if(count == 10)
                {
                    clearInterval(this);
                    countDown();
                    setInterval(countDown, 200);
                }
            }
            function countDown()
            {
                document.getElementById("here").innerHTML = count;
                count--;

                if(count == 0)
                {
                    clearInterval(this);
                    countUp();
                    setInterval(countUp, 200);
                }       
            }
        </script>

        From 0 - 9, up and down:&nbsp;&nbsp;<div id = "here"></div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

xan*_*ded 27

您需要将返回值捕获setInterval( ... )到变量中,因为这是对计时器的引用:

var interval;

function onloadFunctions()
{
    countUp();
    interval = setInterval(countUp, 200);
}

/* ... code ... */

function countDown()
{
    document.getElementById("here").innerHTML = count;
    count--;

    if(count == 0)
    {
        clearInterval(interval);
        countUp();
        interval = setInterval(countUp, 200);
    }
}
Run Code Online (Sandbox Code Playgroud)


Ger*_*ima 6

@Claude,你是对的,我提出的另一个解决方案与原始代码太不一样了.这是另一种可能的解决方案,使用setInterval和切换功能:

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);
}
Run Code Online (Sandbox Code Playgroud)