How is asynchrony possible in JavaScript if JS is single-threaded?
sobes.tech AI
Answer from AI
JavaScript is single-threaded, but asynchrony is achieved through the event loop mechanism and the browser or runtime environment APIs (for example, Node.js).
When an asynchronous operation is called (for example, setTimeout, fetch, file reading), it is passed to the corresponding API, which operates outside the main thread. After the operation completes, the result is placed in the task queue (callback queue).
The event loop constantly checks if the main thread is free, and if so — it takes the next task from the queue and executes it. Thus, asynchronous operations do not block the main thread, and their processing occurs as they become ready.
Example:
console.log('Start');
setTimeout(() => {
console.log('Asynchronous call');
}, 1000);
console.log('End');
The output will be:
Start
End
Asynchronous call
The thread is not blocked waiting for the timer.