Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  9] [ 6]  / answers: 1 / hits: 61823  / 12 Years ago, mon, may 7, 2012, 12:00:00

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>

More From » animation

 Answers
85

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);
}
}

[#85733] Sunday, May 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiejarretk

Total Points: 612
Total Questions: 103
Total Answers: 88

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;