jQuery: Infinite loop that doesn't crash the browser

烈酒焚心 提交于 2019-12-05 18:54:08

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;

For better performance, use requestAnimationFrame instead of setInterval.

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

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

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