Event loop

Javascript runs on machines like Google Chrome's V8 engine or Microsoft's Chakra which are single threaded. This means running a process at a time.

But how does he understand which process to run at once?
It uses a stack call. The satk is always executing the latest item placed on top (LIFO), the Queue is a FIFO system where the message that's been waiting for the longest gets executed first.


It also uses the queue where there are messages that are not needed at the moment. For example, if the Interpreter sees that listening to a function already takes the callback function and puts it at the end of the queue.

Asyncronous and event loop
The setTimeout function is probably the simplest way to asynchronously schedule the code to run in the future:

// Say "Hello."
console.log ("Hello.");
// Say "Goodbye" two seconds from now.
setTimeout (function () {
console.log ("Goodbye!");
}, 2000);
// Say "Hello again!"
console.log ("Hello again!");


If you are familiar with the synchronous code, you might expect the code above to behave in the following way:

Say "Hello".
Do nothing for two seconds.
Say "Goodbye!"
Say "Hello again!"
But setTimeout does not stop the execution of the code. It only schedules something to happen in the future, and then immediately continues to the next line.

Say "Hello."
Say "Hello again!"
Do nothing for two seconds.
Say "Goodbye!"

Conclusion

Trying to avoid asynchronous code and replacing it with a synchronous code is almost always a bad idea in JavaScript because JavaScript only has a single thread (except when using Web Workers). That means the webpage will be unresponsive while the script is running.

Σχόλια