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: <div id = "here"></div>
</body>
</html>
@Claude, you are right, the other solution I proposed was too different from original code. This is another possible solution, using
setInterval
and switching functions:You need to capture the return value from
setInterval( ... )
into a variable as that is the reference to the timer:try this:
you could also create a single reference to
#here
element. Use always===
instead of==
There are many ways to solve this problem, the following is my suggestion:
PS: it's safer to use
setTimeout
thansetInteval
.Console Log shows it's working
clearInterval(this);
. You can't do that. You need to save the return value fromsetInterval
.