Javascript browser: setTimeout and main program

When launched in a browser, will setTimeout ever run its code before executing the main program? Do major browser vendors agree with this behavior or is this a side effect of the implementation? (or they agreed to keep this side effect as standard behavior)

Consider a very simple (and useless) program.

 setTimeout(function(){ console.log("Timeout Called") },1); for(var i=0;i<10000000;i++){}; console.log("done"); 

First, we set a single microsecond setTimeout callback function, which displays the Timeout Called to the console.

Then we rotate in the loop for more than a microsecond.

Then we print done to the console.

When I run this program, it always gives

 done Timeout Called 

That is, the setTimeout callback functions are not taken into account until the main program is launched.

Is this reliable, specific behavior? Or there are times when the main program execution will be stopped, the callback will start, and then the main program will continue.

+4
source share
3 answers

Yes, this is a defined behavior. It is a common misconception that Ajax accesses undefined execution at a particular point in time, possibly before the completion of the current execution path, when in reality they will be executed after some time.

Javascript is single-threaded and will never return to the event loop until the current thread completes execution completely.

An asynchronous function, such as an event handler (including Ajax) or a function that is scheduled using setInterval / setTimeout, will never be executed until the current execution path completes.

+3
source

This is a very well-defined behavior .

The browser is not asynchronous and must still wait for the previous action to complete before it performs the next action

+2
source

When using timeOut it will first wait for the number of milliseconds you passed, and then it will continue to wait until there is an opening in the code. Typically, this means that it will wait until the code is executed. The only exception (view) is the use of other timeOut or setInterval s. For example, if your cycle was

 for(var i=0;i<10000000;i++){ setTimeout(function () { console.log('One iteration'); }, 15); }; 

Your result will be

 done Timeout Called One iteration One iteration 

And so on.

+1
source

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


All Articles