How do create perpetual animation without freezing?

。_饼干妹妹 提交于 2019-12-12 22:51:19

问题


I am still a newbie at 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); 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; 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. So another question: are infinite loops sometimes OK?


回答1:


Since Javascript is asynchornous there is no sleep methode. But instead, a good idea is to use setInterval or 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).




回答2:


Just use callbacks already provided by jQuery animations like .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.



来源:https://stackoverflow.com/questions/19598522/how-do-create-perpetual-animation-without-freezing

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