But wait, What does it mean by synchronous and single-threaded?
Let's deep dive into it
In English, it simply means that something is happening at the same time. And in terms of programming language, it simply means the code will execute in order line by line.
The above code will execute in below order
The above code will output the below result
It's magic --> will display this after 5000ms.
Let's understand this more deeply why and how.
In the above example,
setTimeout will execute asynchronously.
Some examples of browser APIs are fetch, setInterval, DOM methods etc.
Okay, but what does it mean by single-threaded?
In the above example, we saw that
setTimeout was running asynchronously.
But here it won't block the main thread. It will execute outside the callstack.
After timeout, callback function inside the seTimeout will wait in callback queue till the callstack gets empty.
An Event loop constantly keeps checking whether the callstack is empty or not. As soon as it gets empty event loop put callback function from callback queue to callstack and it gets executed.
And there you go ... 🤗🤗🤗
follow me for more such blog posts.
Let me know if this blog was helpful.
Did you find this article valuable?
Support Hemendra Khatik by becoming a sponsor. Any amount is appreciated!