- Heap -> Memory allocation
- Stack -> execution contexts
- Browser, web api
- callback queue
- Event Loop
function main() {
console.log('A');
setTimeout(() => {
console.log('B');
}, 1000); // first 1000, then try with 0 sec
console.log('C');
}
main();
// Output
// A
// C
// B
function main() {
console.log('A');
setTimeout(function exec() {
console.log('B');
}, 0);
runWhileLoopForNSeconds(3);
console.log('C');
}
main();
function runWhileLoopForNSeconds(sec) {
let start = Date.now(),
now = start;
while (now - start < sec * 1000) {
now = Date.now();
}
}
// Output
// A
// C
doA(() => { | first(() => {
doB(); | third();
doC(() => { | fourth(() => {
doD() | sixth();
}); | });
doE(); | fifth()
}); | })
doF(); | second();
function display(data) {
console.log(data);
}
function printHello() {
console.log('Hello');
}
function blockFor3000ms() {
// blocks js thread for 300ms
}
setTimeout(printHello, 0);
const futureData = fetch('https://twitter.com/will/tweets/1'); // response is 'Hi'
futureData.then(display);
blockFor300ms();
console.log('I am good!');
'I am good', 'Hi, 'Hello' instead of 'I am good', 'Hello', 'Hi'
since there is a two callback queue: MicroTask Queue and Callback Queue. Promise goes to microTask queue. When callStack is empty the event loop check microTask queue first then check callBack Queue!
Hold promise-deferred functions in a microtask queue and callback function in a task queue (Callback queue) when the Web Browser Feature (API) finishes.
Add the function to the Call Stack (i.e. run the function) when:
- Call Stack is empty & all global code run (Have the Event Loop check this condition)
Prioritize functions in the microtask queue
over the Callback queue.