I have a bunch of functions that calls another function. I want to run those group of functions in an infinite loop and can't really come up with a logic.
My code looks like this:
<script>
function runAnim(x,y) {
//animation code
}
runAnim(a,2);
setTimeout(function() {
$('#a').fadeOut('fast');
}, 3000);
runAnim(b,4);
setTimeout(function() {
$('#b').fadeOut('fast');
}, 3000);
</script>
So I want to run these two 'runAnim' functions in an infinite loop. I tried
while(1) {}
but this hangs up my browser. I tried implementing setInterval method but don't know how I can do this. If you want I can post the runAnim(x,y) function for more clarity.
Change your runAnim
method to include a call to runAnim
via setTimeout
so that you can an infinite loop while ensuring that maximum stack isn't exceeded .
function runAnim(x,y) {
//animation code
if ( y == 2 )
{
setTimeout( () => {
runAnim(x,4);
$('#a').fadeOut('fast'); //call the fadeout here itself
}, 3000 );
}
else
{
setTimeout( () => {
runAnim(x,2);
$('#a').fadeOut('fast');
}, 3000 );
}
}
You don't need an explicit infinite loop, you can just let the functions call the other one over and over again
Here is an example with chaining:
function fadeOutA() { $('#b').fadeIn('fast'); $('#a').fadeOut('fast', fadeOutB); } function fadeOutB() { $('#a').fadeIn('fast'); $('#b').fadeOut('fast', fadeOutA); } function stop() { $('#a, #b').stop(); } $('#start').click(fadeOutA); $('#stop').click(stop);
div { width: 50px; height: 50px; float: left; margin: 10px; } #a { background-color: green; } #b { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="a"></div> <div id="b"></div> <button id='start'>START</button> <button id='stop'>STOP</button>
What i suggest is don't write any logic which run is infinite loop, because it will cause problem for your browser. But event if you want it to be done done something like below
create for loop for(var i=0;;i++){}
and then place your function inside this loop which will execute unlimited times.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.