Answer the question
In order to leave comments, you need to log in
How is asynchronous behavior implemented in programming languages?
How is asynchronous behavior implemented in programming languages? Through multithreading or through the OS API or...
In particular, I wonder how asynchrony is implemented in javascript. Is it achieved using the setTimeout, setInterval functions and the XMLHTTPRequest? If so, how are these functions implemented?
Answer the question
In order to leave comments, you need to log in
There are many ways to implement: OS threads, coroutines (coroutines) , event approach .
Specifically, JavaScript is single-threaded, and it uses the latter method. When calling setInterval/setTimeout inside the js engine, an object is created that links the timer and the callback (event handler). Each tick engine checks if the timer has expired and if it has, it adds a callback to the call queue. XMLHTTPRequest works similarly, but instead of "expiring", it "waits" for a response from the server.
Useful links:
In JS, this behavior is implemented through the Event Loop. This is a mechanism that allows you to bind events (timer expiration, response to a request, an explicitly raised event) and a handler function that is called after this event has occurred. Bold means that the function will not be called immediately after the event occurs, but at an arbitrary point in time after. Those. it will not be called before the event happens, but exactly when it will be called after it occurs depends on when the Event Loop gets control again, i.e. there is no concept of interrupt - the handler will not be called while some other function is executing. Accordingly, as soon as there are no more running or waiting functions in the Event Loop, the program ends.
setTimeout(function() { console.log('Timeout 1000'); }, 1000 );
setTimeout(function() { console.log('Timeout 2000'); }, 2000);
console.log('Now!');
Now!
Timeout 1000
Timeout 2000
In multithreading languages, synchronization objects use either a type library or the capabilities of the language itself. Much of this is indirectly translated into the OS API, but we do not use the API directly. Because this is a very important point for both reliability and performance and is being worked out at the stage of creating the language itself. And because it's syntactically simpler.
JavaScript is natively single-threaded. But now browsers allow you to run background threads, in fact it is a separate process with its own window object. And communicate between the main and background processes using messages. Thus, you can run heavy algorithms in the background. But for the purposes of scripting the page, this, of course, cannot be used.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question