Understanding Threading / Synchronicity via JS setTimeout

The Javascript setTimeout function makes me overestimate the little that I know about javascript. Earlier today, I came across a for loop as follows:

for (i = 0; i < length; i++) { setTimeout(executeOtherCode, 5000) } 

I expected this code to execute the executeOtherCode function, "sleeping" for 5 seconds and continue the next iteration. Instead, I got executeOtherCode running the duration at the same time.

So, from my understanding, setTimeout is an asynchronous function call. It's right? However, if I were to perform a regular function, let it call it a huge function (), which takes 1 minute to execute, the following lines of code will not execute until this function returns anything, right? So why are they different? Only a choice of language?

I saw other functions in jQuery that behave similarly asynchronously, like getJSON. Is it just a question of which functions were defined as asynchronous or is there some kind of template for identifying them? If yes, then?

+4
source share
1 answer

As a rule, except in special cases - JavaScript is executed synchronously and in order.

 setTimeout(executeOtherCode, 5000) 

Says "After 5 seconds, run the executeOtherCode function executeOtherCode " It continues to run the loop; it does not perform a “lock”.

After 5 seconds, the event loop will notice that the timer (well, length timers) has been configured and will execute them (one after the other).

If you want the functions to be executed in a 5 second delay of each other, you need to tell the next function to execute 5 seconds after the last one is completed, this template is called an asynchronous semaphore.

The general rule is that if it performs I / O, it must be asynchronous , so AJAX is asynchronous (as well as other HTTP requests, such as a script tag) and the interaction of an event is asynchronous (JavaScript responds to clicks, for example, he does not wait for them). Timers (setTimeout and setInterval are also asynchronous).

Everything else is synchronous.

Now some functions can use these other functions, but there is no silver bullet in determining what is. Just clear the documentation. Most asynchronous functions have a callback parameter (for example, the first executeOtherCode parameter), but some do not, and some functions accept callbacks, but are not asynchronous.

+6
source

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


All Articles