Richie Richie - 6 months ago 46
jQuery Question

jQuery: Infinite loop that doesn't crash the browser

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!

Answer

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;