0

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.

Marcos Di Paolo
  • 527
  • 1
  • 5
  • 22

1 Answers1

0

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.

mmdts
  • 757
  • 6
  • 16
  • `var animacionFlechas = function(){ $('.up') .animate({ 'bottom': '30px' }, 500) .animate({ 'bottom' : '20px' }, 500); $('.down') .animate({ 'bottom': '10px' }, 500) .animate({ 'bottom' : '30px' }, 500); } setInterval(animacionFlechas, 1000);` – Marcos Di Paolo Apr 22 '18 at 02:06
  • thanks!! mmdts!!!, this wasn't a duplicate, for the geniuses that banned the question – Marcos Di Paolo Apr 22 '18 at 02:07
  • It was. Check the answer of the question the "actual geniuses" that banned the question referred to: https://stackoverflow.com/questions/5835126/javascript-infinite-loop It elaborates much more than my answer does. People don't reach 80K reputation out of not knowing what questions are duplicates. – mmdts Apr 22 '18 at 02:08
  • Thanks mmdts, I'll check that out again, probably i overlooked something – Marcos Di Paolo Apr 22 '18 at 03:47