如何正确使用 setInterval 和 clearInterval 在两个不同的函数之间切换? [英] How do I correctly use setInterval and clearInterval to switch between two different functions?

查看:26
本文介绍了如何正确使用 setInterval 和 clearInterval 在两个不同的函数之间切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

到目前为止我所拥有的代码似乎很接近,但是在第二次迭代时,我的两个函数 countUpcountDownsetInterval 调用似乎相互冲突,因为显示的数字是不按预期顺序计算......然后浏览器崩溃.

这是我的代码:

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 be close, but upon the second iteration the setInterval calls of my 2 respective functions countUp and countDown seem to be conflicting with each other, as the numbers displayed are not counting in the intended order... and then the browser crashes.

Here is my code:

<!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>

推荐答案

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

You need to capture the return value from setInterval( ... ) into a variable as that is the reference to the timer:

var interval;
var count = 0;

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

/* ... code ... */

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

    if(count === 10)
    {
        clearInterval(interval);
        countUp();
        interval = setInterval(countUp, 200);
    }
}

这篇关于如何正确使用 setInterval 和 clearInterval 在两个不同的函数之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆