Why can't we use a for loop to create an animation?

Using the jQuery library and the offset () method, it seems logical to think that by writing this simple code, the element will gradually change position

for (i = 0; i < 900; i = i + .5) { $('#moving-element').offset({ top: i }) } 

The browser will stop for a while and, finally, move the element to the 900px position separately from the top, the transition will not be observed. Out of curiosity, I wrote this:

 for (i = 0; i < 900; i = i + .5) { $('#moving-element').offset({ top: i }); console.log(i) } 

to see the console display a sequence of numbers in order, but it only shifts the item after the for loop completes.

Why is this not done gradually while executing the code?

+6
source share
2 answers

Since javascript is a single-threaded event, simulated runtime (at least in current incarnations).

This means that during the execution of the for loop, no other tasks can be performed. This means accepting user input, updating the screen, etc. Thus, the cycle goes through completely and then displays the final result.

+5
source

The problem is that javascript is single-threaded and it blocks the queue of ui and events during processing. You need to use setTimeout or some other asynchronous flow control mechanism to generate drawing tasks, to insert into the event loop, so that the browser can do other things during the animation.

 // Our animate function changes the offset, waits a while, then repeats function animate(n) { // Change the offset to the passed in value $('#moving-element').offset( {top: n}); // If the passed in value is equal to 900, stop exection if (n === 900) return; // Otherwise, set a timer which will trigger our animate function again // after 10 milliseconds setTimeout(function() { // Increment n when passing it into our function animate(n++): }, 10); } // Call the function to begin with animate(0); 

Here is a JSFiddle example that will give you some insight into how fast the for loops are. After clicking the button, the for loop starts execution, and only when it reaches its millionth iteration does it display a warning on the screen.

+5
source

Source: https://habr.com/ru/post/973866/


All Articles