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

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

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

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('

Test 1

'); $(this).animate({ width: "500px", height: "500px", }, 500 ); }else if (($(this).position().left) < ($(window).width() * 0.2)) { $(this).html('

Test 1

'); $(this).animate({ width: "600px", height: "600px", }, 500 ); } }); }

任何提示都会很棒!

尝试使用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('

Test 1

'); $(this).animate({ width: "500px", height: "500px", }, 500 ); }else if (($(this).position().left) < ($(window).width() * 0.2)) { $(this).html('

Test 1

'); $(this).animate({ width: "600px", height: "600px", }, 500 ); } }); } var interval = self.setInterval(function(){LoopForever()},3000); //call code bllow to stop interval //window.clearInterval(interval);

注意:1000 = 1秒;

为了获得更好的性能,请使用requestAnimationFrame而不是setInterval。

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

jQuery动画可以链接,因此要运行一个动画然后运行另一个动画,你可以调用两次动画。 也可以使用.queue(回调(下一个))将非动画添加到队列中。

jsFiddle演示

 
Hi
​ .hello { position: relative; width: 100px; height: 100px; background: red; }​ $(".hello") .animate({ left: 200 }) .animate({ width: 200, height: 200 })​

额外提示:如果你想要一个无限循环,只需将true传递给while: while (true) { ... }