jQuery:无限循环,不会使浏览器崩溃

Ric*_*hie 3 jquery loops infinite-loop

我想知道是否有可能创建一个无限制的循环,它不会使浏览器崩溃,我正在处理一个类型的画廊,它会在屏幕上滚动时产生脉冲.

这是我到目前为止(显然崩溃浏览器):

    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 );
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

任何提示都会很棒!

Hab*_*lah 9

尝试使用window.setInterval(),如下面的代码(它将以3秒的间隔执行):

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);
Run Code Online (Sandbox Code Playgroud)

注意:1000 = 1秒;