Currently watching a Youtube video that explains the Call Stack and Event loop when dealing with Async events like Ajax calls. According to the video, JavaScript execution occurs line by line. Let's try running a sample program:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText);
}
};
xhttp.open("GET", 'https://httpbin.org/get', true);
xhttp.send();
let i = 1;
while (i < 1000000000) {
i++;
}
console.log(i);
Based on my understanding from the video, the JS Engine will place the Ajax call in the Call Stack and execute it. Since the Ajax call takes some time, the callback will be moved to Web APIs by the browser and the code continues executing (in this case, the while loop). Once the Ajax call is complete, the Web APIs will add the callback to the Task Queue. If the Call Stack is empty, the Event Loop will push the callback back onto the stack for execution. In our example, I purposely made the loop count large to make the Event Loop wait until the while loop finishes even though the Ajax call is done. However, when I ran the program, the Ajax call was only made after the while loop completed. This raises the question of why we put the Ajax call before the while loop. I expected the Ajax call to be triggered immediately but the response to be printed after the loop finished. Is there something that I have misunderstood?