What Is Asynchronous Programming

you write a script that sets up a click handler for a mouse click, and also sends a request to get more data using XHR (XMLHttpRequest, also known as Ajax).

Your request to get more data might be initiated right away, but if it takes a while to get the data, the event handler that will be called once the data is received won’t execute for a while.

In the meantime, you can click your mouse a bunch of times and your mouse click event handler will execute. The XHR request that you created to get more data is executed asynchronously.

That is, the browser allows you to do other things while it’s waiting to get the data from the XHR request.

In fact, while it’s waiting for the data, the browser goes back to executing the event loop so it can respond to other events. When the data you requested with XHR is finally retrieved, your XHR event handler will be executed.

Compare the way the browser handles a synchronous loop, like we created above, with the way it handles an asynchronous request like XHR: The loop jams up the event loop, while the XHR request does not.

<!doctype html>
<html>
<head>
    <title> XHR Asynchronous Request>
     <meta charset="utf-8">
      <script>
           window.onload = function() {
               document.onclick = function() {
                    alert("You clicked on the web page!");
             }
              var request = new XMLHttpRequest();
              request.open("GET", "data.json");
              request.onreadystatechange = function(response) {
                   ar div = document.getElementById("div1");
                   if (this.readyState == this.DONE && this.status == 200) {
                       if (response != null) {
                           div.innerHTML = this.responseText;
                 }
                    else {
                          div.innerHTML += "Error: Problem getting data";
                        }
                 }
                    else {
                        div.innerHTML += "Error: " + this.status;
                      }
                }
                 request.send();
            }
</script>
</head>
<body>
   <div id="div1"></div>
</body>
</html>

Our data is small so it doesn’t take much time to retrieve, so the browser will load your JSON data far too fast for you to be able to click on the page before it does.

Still, you can see from the code that we’re setting up two events: one will occur whenever you click the mouse, and the other will occur when the data in the file “data.json” has been retrieved.

We have no way of knowing which will occur first (but we can make an educated guess because you can’t click the mouse fast enough). If you never click the mouse, then the mouse click event will never happen.

If you replace the small amount of data here with a much larger amount of data, you might be able to delay the loading long enough to click the mouse. Give it a try if you want.

Remember, JavaScript in the browser is event-driven; once the browser has loaded and executed your code in the first phase (as it loads the page), the second phase responds to events, which makes your web pages interactive.

Also keep in mind that some actions, like XHR requests, are executed asynchronously. We set up XHR event handlers like we do other kinds of event handlers: by assigning a function to a property on an object, in this case, the XMLHttpRequest object.

The event handler is called when the data requested by the XHR request has been returned to the browser.

We don’t know precisely when the event will occur, and because the browser doesn’t stop the event loop while it’s waiting for the data, we can continue to interact with the browser
and run other code.

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Asynchronous Programming In JavaScript

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password