3
setTimeout(() => {
  console.log('1st callback function');
}, 1000);

fetch('https://api.netflix.com').then(() => {
  console.log('2nd callback Function');
});

These both are the Callback Function but as i heard that setTimeout callback function will go inside the Task queue/Callback queue and fetch Callback function is go inside the Micro Task Queue. so what the reason behind this?

4
  • 1
    You can read about priority, I think that related to that. stackoverflow.com/questions/19743354/… Commented Feb 5, 2021 at 7:40
  • 3
    You can read on this from here - javascript.info/event-loop. Not really a StackOverflow type of question since the reasoning has to do with event loop architecture. Had your question be like why Promise callback executes before setTimeout one, that would be a valid question for StackOverflow but since you're already familiar with the term 'microtask', go look it up. Commented Feb 5, 2021 at 7:40
  • 1
    Promises always use the microtask-queue, so promise chains that resolve immediately can run before a timeout callback fires. Commented Feb 5, 2021 at 8:01
  • 2
    Your example is misleading. If the 1000ms setTimeout() resolves faster than the fetch it will come first however functions like fetch those returns promises get registered to the micro task queue and have precedence over the event queue. However this is only a choice when they get resolved at the same time. Commented Feb 5, 2021 at 19:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.