true as a condition in a javascript while loop [duplicate]

落爺英雄遲暮 提交于 2020-01-06 07:26:30

问题


I was wondering why this code crash my browser:

while (true) {
    $('.selector')
        .animate({ 'bottom': '30px' }, 500)
        .animate({ 'bottom' : '20px' }, 500);
}

and this other code works (without true as a condition)

var a = 0;
while (a < 1000) {
    $('.selector')
        .animate({ 'bottom': '30px' }, 500)
        .animate({ 'bottom' : '20px' }, 500);
    a++;
}

If i would dare to answer the question myself i'd say that the second code fill a queue of 1000 actions and stops when the first one never finishes and crash the browser.
I need it to be infinite but not going to the next iteration until the animations are complete. I was playing with stop(); here and there but it didn't do the trick.


回答1:


If you're trying to do what I think you're trying to do, try considering using window.setInterval

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

while(true) just runs forever! It never stops.

To explain why a loop that runs forever crashes the browser, consider the following example:

Joe can execute 1000 commands per second. You are a fast speaker, so you can give Joe a million commands per second. If you give Joe 7000 (will take you 7 milliseconds) commands and stop, Joe will take seven seconds to execute them and stop.

Now imagine what happens when you give Joe an infinite number of commands (as in a while(true)... Joe will never be able to catch up to you since you keep giving him commands and he can't process them all, his brain will start to hit him, and he won't be as responsive, if responsive at all.

Your browser is Joe. It runs on a single thread (one core), has limited resources, very high overhead, and runs a relatively very processor-inefficient language (Javascript).

This analogy isn't the most technically accurate one considering how processors work, but it should get the point across.



来源:https://stackoverflow.com/questions/49961768/true-as-a-condition-in-a-javascript-while-loop

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