对于练习,我试图显示一个从0到9递增的数字,然后从9到0递减,并无限重复。
我到目前为止的代码似乎很接近,但在第二次迭代时,我的2个函数countUp
和countDown
的setInterval
调用似乎彼此冲突,因为显示的数字不按照预期顺序计数。 ..然后浏览器崩溃。
这里是我的代码:
如何正确使用setInterval和clearInterval在两个不同的函数之间切换?
<!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>
谢谢,这是做诡计! –