为了练习,我尝试显示一个从 0 - 9 递增,然后从 9 - 0 递减,并无限重复的数字。
我到目前为止的代码似乎很接近,但是在第二次迭代时,我的两个函数 countUp
和 countDown
的 setInterval
调用似乎相互冲突,因为显示的数字是未按预期顺序计数...然后浏览器崩溃。
这是我的代码:
<!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: <div id = "here"></div>
</body>
</html>
最佳答案
您需要将 setInterval( ... )
的返回值捕获到一个变量中,因为它是对计时器的引用:
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);
}
}
关于javascript - 如何正确使用 setInterval 和 clearInterval 在两个不同的函数之间切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485385/