View Full Version : Invoke Function Loop: This script works without a loop or while loop. explain why?

04-26-2009, 12:40 AM
Hi all.
Just a script i've been working on to learn local and global variables.
I was under the impression that the only way a script could loop is by using FOR/WHILE or DO loops.

Here i have used if/else statements and invoked a function within a function (on both functions). The consequence of this has been a continuous loop between both functions until the else statement is resolved.

Can anyone explain why this happens. I like the results. I just need to understand why

1. Break is not required after the else statement is satisfied to break the loops
2. this script loops irrespective of a for/loop statement


<script type="text/javascript">
this random counter is programmed with local variables within one function:
var - number - is a GLOBAL variable of - random_counter()

The declaration of a GLOBAL variable as the value of the random math function means
The result is that:
- random_counter5()
declares a new random value that is passed onto
- declare_global5()
the functions loop until the else statement is satisfied


//random counter 20
function random_counter5()


number5 = Math.floor(Math.random()*20) +1
document.write('random internal ' + number5 + '<br />');

function declare_global5()

if (number5>=1 && number5<=19) {
document.write(' global internal ' + number5 + '<br />');
else {
if (number5==0 || number5==20)
alert("The number reached has been a zero or twenty");



The script is called via a form button onclick event handler.

<input type="button" value="random counter five" onclick="random_counter5();">

you can find my scripts at [removed link by request] :)

04-26-2009, 01:12 AM
A loop is simply a process that continues until stopped. It doesn't require a for, a do while, or a while.

You can make a loop in a number of ways, this is just another way - one function calling another which calls the first function until a condition is satisfied.

04-26-2009, 01:32 AM
one function calling another which calls the first function until a condition is satisfied.

thanks for the reply. i'm still confused though because in my script, the condition is satisfied when:

if (number4>=1 && number4<=19)

is TRUE (if a random number is between 1-19)
and then writes the number to the screen
and then calls back to the original function

Sorry if i seem naive, but there must be several conditions in the script, which one specifically causes the invoke function loop??

04-26-2009, 03:10 AM
Just follow the logic. There is no way to know for sure what number will be generated in any given cycle. As long as the number generated satisfies:

number5>=1 && number5<=19

(1 to 19) the loop will continue.