Can we run a loop on a function in javascript, so that the function executes several times?
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
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();
}
Learn basic JavaScript at W3Schools. It's well worth the effort - it won't take long.
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>