m having a problem with nested SetInterval’s.
My goal is to repeat an animation of blocks showing in equal intervals.
So my first iteration goes well and each block appears in equal intervals and then all disappear as planned.
But problems start from the second iteration.
They begin to show randomly and in totally different intervals.
Here’s my code you can copy it and see the behavior by yourself:
<style type="text/css">
#wrap{width:700px; min-height:700px; margin:0 auto; }
#wrap div+div,#wrap div+div+div,#wrap div+div+div+div{width:70px; height:70px; position:absolute; display:none;}
#wrap div+div{top:340px; left:370px; background-color:#2e9555 }
#wrap div+div+div{top:340px; left:470px;background-color:#dfe766; }
#wrap div+div+div+div{top:340px; left:570px; background-color:#1a3c65;}
</style>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript" >
$(function(){
popups();
});
var y;
setInterval(popups,1200);
function popups(){
var x=1;
y =window.setInterval(function(){ popUpBuble(x); ++x;}, 1200);
};
function popUpBuble(index){
if(index<4){
$('#wrap div:eq('+index+')').fadeIn('slow');
}
else{
window.clearInterval(y);
$('#wrap div:lt(4)').delay(3000).fadeOut(1000);
}
}
<body>
<div id="wrap">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</body>
Any ideas how to fix the bug and also how do you minimize the resources taken by setInterval.
It rises memory use every second.
The main issue here is that your time interval for the first
setIntervalis too small. This call topopupsre-starts the overall animation. If you are trying to start the animation while it is already in motion, this is a problem.Increasing the interval to be longer than the overall animation fixes this:
http://jsfiddle.net/9ZwwN/
I would however suggest a slightly different approach, though. The nested interval thing as you can see gets very confusing. You may want to consider using callbacks on your animations instead along with
delayto remove the intervals all together.