loop on a function in javascript?
Can we run a loop开发者_如何学C 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
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>
for (var i=0;i<10;i++) //Loop 10 times
{
//Do something
}
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();
}
Here is another way to iterate (functionaly) over a function, that is also
optimised (using loop unrolling), on average it will be up to 16
times faster
(adapted from a functional lib of mine use as you wish)
function iterate( F, i0, i1, F0 )
{
if ( i0 > i1 ) return F0;
else if ( i0 === i1 ) { F(i0, F0, i0, i1); return F0; }
var l=i1-i0+1, i, k, r=l&15, q=r&1;
if ( q ) F(i0, F0, i0, i1);
for (i=q; i<r; i+=2)
{
k = i0+i;
F( k, F0, i0, i1);
F(++k, F0, i0, i1);
}
for (i=r; i<l; i+=16)
{
k = i0+i;
F( k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
F(++k, F0, i0, i1);
}
return F0;
}
use example:
function iterated(i, a, i0, i1)
{
console.log([i, i0, i1]);
a.push(i);
}
var a = iterate(iterated, 0, 9, []); // optionaly one can pass a parameter in the iterator
console.log(a);
output:
[0, 0, 9]
[1, 0, 9]
[2, 0, 9]
[3, 0, 9]
[4, 0, 9]
[5, 0, 9]
[6, 0, 9]
[7, 0, 9]
[8, 0, 9]
[9, 0, 9]
[0,1,2,3,4,5,6,7,8,9]
精彩评论