jQuery: Infinite loop that doesn't crash the browser

旧时模样 提交于 2019-12-22 10:42:06

问题


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!


回答1:


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;




回答2:


For better performance, use requestAnimationFrame instead of setInterval.

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame




回答3:


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)).

jsFiddle Demo

<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) { ... }.



来源:https://stackoverflow.com/questions/13020630/jquery-infinite-loop-that-doesnt-crash-the-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!