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?

  • 1
    You can read about priority, I think that related to that. https://stackoverflow.com/questions/19743354/does-javascript-event-queue-have-priority – Abhinav Kumar Feb 05 '21 at 07:40
  • 3
    You can read on this from here - https://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. – Lakshya Thakur Feb 05 '21 at 07:40
  • 1
    Promises always use the microtask-queue, so promise chains that resolve immediately can run before a timeout callback fires. – FZs Feb 05 '21 at 08: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. – Redu Feb 05 '21 at 19:46

0 Answers0