HTML and CSS Reference
In-Depth Information
EXAMPLE
7.11
<html>
<head>
<title>Recursion</title>
<script type="text/javascript">
1
function upDown(num)
{
2
document.write("<b><font size='+1'>
Level
"
+
num
+ "</b><br />");
3
if(num < 4){
4
upDown(num + 1);
//
Function calls itself
5
document.write("<em>Level "+ num + "<em><br />");
}
}
</script>
</head>
<body bgcolor="lightblue">
<h2>Recursion</h2>
<script type="text/javascript">
6
upDown(1);
</script>
</body>
</html>
EXPLANATION
1
The first time this function is called it is passed the number 1.
2
The function prints out the level number, Level 1.
3
If the value of
num
is less than
4
, the function calls itself.
4
When the function calls itself, it adds 1 to the value of
num
and restarts execution
at the top of the function, this time with the value of
num
equal to
2
. Each time
the function calls itself, it creates a new copy of
num
for that recursion level. The
other copy is on hold until this one is finished. The function keeps calling itself
and printing level numbers in bold text until the
if
statement fails; that is, until
the value of
num
is not less than 4.
5
This line won't be executed until the recursion stops—when the value of
num
is
4
. When that happens, the current version of
upDown()
is finished, and we back
off to the previous called function and start execution at line 5. This process con-
tinues until all of the functions have completed execution.
6
This is the first call to the
upDown()
function. The argument is the number
1
. The
output is shown in Figure 7.16.