- Javascript is a Synchronous single-threaded language. it can do 1 thing at a time.
- Call stack present in the JS engine all code executes in the call stack.function a(){console.log('I am a()');}a();console.log('End')
- Whenever the js engine runs the code it runs from top to bottom. it runs line by line.
- Function a will be allocated memory & will be stored in call stack.
- a() will be pushed at a call stack & function a is executed. after executing a will be popped out from the call stack.
- And so on...
WEB API's
- setTimeOut()
- DOM API'S ( document.getElementByID() )
- fetch
- localStorage
- console
- location
These are not part of javascript, These are part of Browser. WEB API's present in the global object window.
window.console.log('Rahul More')
We can even write like this to get an appropriate output. but we don't have to write `window` each time because it's present in Global Object. so we can write it as
console.log('Rahul More')
Example
console.log('start');
setTimeout(function cb() {
console.log('Callback')
}, 5000);
// this will go to callstack after 5 seconds as we
// have passed this delay! Through the call back queue.
console.log('end');
The above code can generate output like this
Event Loop & Callback
- Callback goes the call stack through the callback queue.
- The event loop continuously checks in Callback QUEUE for callback & adds it to the call stack.
Call Back Queues
- A lot of calls back stored in CB queues & pushed into call stack one by one using an event loop.
Micro stack Queues.
- Fetch API.
- Fetch API doesn't work like other web APIs like setTimeOut(), DOM APIs, instead of fetch APIs go inside Micro stack Queue.
- It is like call back queue But has a higher priority than Call Back queue as you can see that in the image.
What comes inside Micro Stack Queues
- Promises
- Mutation Observer.
What comes inside Micro Stack Queues
- SetTimeOut
- DOM API'S.
Starvation.
- Suppose there are a lot of tasks in the Micro stack queue & one task is creating another task in the Micro stack queue then the task in the callback queue will not get a chance to execute because of priority reasons.
- This is known as starvation. starvation of the tasks inside the callback queues.
0 comments:
Post a Comment