问题
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