[英]How do create perpetual animation without freezing?
I am still a newbie at Javascript. 我仍然是Javascript的新手。 I tried writing a program to make images fadeToggle all the time, so I used the while conditional statement (combined with a constant variable); 我试图编写一个程序使图像始终保持淡入淡出状态,因此我使用了while条件语句(结合了常量变量); after running that and freezing my computer (then remembering that viruses are basically infinite operations) I searched on here a bit, realized I should probably, indeed, never use infinite loops. 在运行并冻结我的计算机(然后记住病毒基本上是无限操作)之后,我在这里进行了一些搜索,意识到我实际上应该永远不要使用无限循环。
(Actually I want shimmer -- meaning to go from opacity 0.9 to 0.6 to 0.9 etc...) so its not the same as fadeToggle, but the same question remains; (实际上,我想要微光-意味着从不透明度0.9变为0.6到0.9等...)因此它与fadeToggle不一样,但是仍然存在相同的问题; how do I make it go infinitely?(without writing malicious code.) 我如何使其无限发展(无需编写恶意代码)。
This is what I wrote, for your reference: 这是我写的,供您参考:
<script>
$(document).ready(function(){
var always10 = 10;
while (always10 == 10) {
$('.pimg').fadeToggle(2600);
}
});
</script>
Also, I've found out on another thread that while(true)
is better for infinite loops. 另外,我发现在另一个线程上, while(true)
更适合无限循环。 So another question: are infinite loops sometimes OK? 因此,另一个问题是:无限循环有时可以吗?
Just use callbacks already provided by jQuery animations like .fadeToggle : 只需使用jQuery动画(如.fadeToggle)已提供的回调:
function fadeToggleForever ($e) {
$e.fadeToggle({
duration: 2600,
// start another fadeToggle when this one completes
complete: function () { fadeToggleForever($e) }
});
}
// main code
fadeToggleForever($('.pimg'));
The of using the complete callback works because jQuery animations internally use setTimeout
(or perhaps setInterval
) and thus "yield" code execution so that the browser can continue reacting to user input and updating the display. 之所以使用完整的回调,是因为jQuery动画在内部使用setTimeout
(或者可能是setInterval
),从而“屈服”了代码执行,因此浏览器可以继续对用户输入做出反应并更新显示。
Since Javascript is asynchornous there is no sleep
methode. 由于Javascript是异步的,因此没有sleep
方法。 But instead, a good idea is to use setInterval
or setTimeout
. 但是,一个好主意是使用setInterval
或setTimeout
。
Without these function, your loop is going to take as most ressources as it can and it can result in a freeze (depending on your browser). 没有这些功能,您的循环将占用尽可能多的资源,并且可能导致冻结(取决于浏览器)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.