tags:

views:

84

answers:

5

Can we run a loop on a function in javascript, so that the function executes several times?

+2  A: 

Yes, you can use a for loop and a while loop in javascript

for (i=0;i<=5;i++)
{
    MyFunc();
}

Where the variable 'i' is the number of times it needs to run

jmein
but how? plz tell me
Sheery
the answer tells you exactly how to do it...
KP
@KP At the time I didnt have the code in there but the for and while are links to code on w3schools. I guess they didnt notice that so I added the code as well.
jmein
A: 
for (var i=0;i<10;i++) //Loop 10 times
{
//Do something
}
Richard Friend
+1  A: 

Assuming your function is called f.

function f()
{
    ...
}

Here is a Javascript loop that will run your function 10 times.

for( int i = 0; i < 10; ++i )
{
    f();
}
Vincent Robert
A: 

Learn basic JavaScript at W3Schools. It's well worth the effort - it won't take long.

Skilldrick
hmmmm, thanks for you advice.
Sheery
A: 

if you tired of using standard like (IF, WHILE), here is the another way of doing.. :)

you can use setTimeOut and clearTimeOut to execute functions in a certain interval. If you want to execute an function for a specific number of times, you still can acheive it by incrementing index and clearTimeOut as soon as your index reaches to certain point.

setTimeout() - executes a code some time in the future

clearTimeout() - cancels the setTimeout()

example from w3schools

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>
Jeeva S