Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 548
Richie Avatar asked Oct 18 '25 18:10

Richie


1 Answers

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;

like image 99
Habibillah Avatar answered Oct 22 '25 06:10

Habibillah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!