Reputation: 366
I was wondering if it was possible to create an infinite loop which does not crash the browser I am working on a gallery type thing which will pulse as it scrolls across the screen.
This is what I have so far (which obviously crashes the browser):
var i = 0;
while (i < 1){
$('.block').each(function(index) {
$(this).css('left', $(this).position().left - 10)
if (($(this).position().left) < ($(window).width() * 0.4)) {
$(this).html('<p>Test 1</p>');
$(this).animate({
width: "500px",
height: "500px",
}, 500 );
}else if (($(this).position().left) < ($(window).width() * 0.2)) {
$(this).html('<p>Test 1</p>');
$(this).animate({
width: "600px",
height: "600px",
}, 500 );
}
});
}
Any tips would be grand!
Upvotes: 4
Views: 16600
Reputation: 21
For better performance, use requestAnimationFrame instead of setInterval.
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
Upvotes: 2
Reputation: 37771
jQuery animations can be chained, so to run one animation then run another, you can call animate twice. It is also possible to add non-animations into the queue using .queue(callback(next)).
<div class="hello">Hi</div>
.hello {
position: relative;
width: 100px;
height: 100px;
background: red;
}
$(".hello")
.animate({ left: 200 })
.animate({ width: 200, height: 200 })
Bonus tip: if you want an infinite loop, just pass true into while: while (true) { ... }
.
Upvotes: 0
Reputation: 28695
Try to use window.setInterval() like code bellow (it will be execute with interval 3 second):
function LoopForever() {
$('.block').each(function(index) {
$(this).css('left', $(this).position().left - 10)
if (($(this).position().left) < ($(window).width() * 0.4)) {
$(this).html('<p>Test 1</p>');
$(this).animate({
width: "500px",
height: "500px",
}, 500 );
}else if (($(this).position().left) < ($(window).width() * 0.2)) {
$(this).html('<p>Test 1</p>');
$(this).animate({
width: "600px",
height: "600px",
}, 500 );
}
});
}
var interval = self.setInterval(function(){LoopForever()},3000);
//call code bllow to stop interval
//window.clearInterval(interval);
Note: 1000 = 1 second;
Upvotes: 10