Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Debug Asynchronous JavaScript with Chrome DevTools?

In order to go through a full detail of asynchronous JavaScript callbacks, Chrome DevTools offers a new unique view feature, which can be very useful for developers. This is what we are going to look into in this tutorial.

Why debug asynchronous code?

One of the most powerful features of JavaScript, as a scripting language, is its ability to work asynchronously by means of callback functions. Now, with asynchronous code, it helps developers implement callbacks and thus write code that is largely event driven. However, considering that execution of such type of code takes place in a non-linear fashion, it can be a tumultuous task for a developer to debug such code. This is why Chrome DevTools offers this amazing viewing feature, where you get to see the complete stack of callbacks executed for your code.

On enabling the async call stack feature on Chrome DevTools, you, as a developer, will have the ability to look into the state of your web app at every point of time. Some of the common stuff comprises of going through the event listeners, such as XMLHttpRequest, setTimeout, setInterval, promises, requestAnimationFrame and a whole lot more. Also, during your walk through the stack, you will be able to even view the value of any variable that you wish to at any specific point of time. Basically, it acts as a complete time machine that allows you to view all that you need to.

We shall now learn to activate this feature and then get going with a few tasks.

Enabling of Async Call Stack

To try out the async call stack feature that is offered in Chrome DevTools, you can visit the Sources panel of Chrome Canary DevTools. Then look for the Call Stack panel, which can be found on the right hand side, and check the box that is present right beside Async. Toggling the checkbox will either turn it on or off.

Figure 1. Chrome Dev tool window

Now that we are set, we will take a look at some the things that you can do with this feature enabled to your advantage.

Capturing delayed timer events & XHR responses

One of the issues that you night have faced pretty often is with Gmail. Something like this happens.

Figure 2. Sending request

Now, this is mainly a problem that concerns the sending of the request, either the server has been facing problems or there is a network connectivity issue on the client side. However, what Gmail does to recover from such a situation is to try and resend the message after a short timeframe.

If you wish to see how async call stacks can actually help us see and study delayed timer events and XHR responses a flowchart has been provided to assist you. You can also do a demo run of the code provided for your perusal.

Listing 1: Sample demo run

<!DOCTYPE html>
<html>
  <head>
    <title>XHR Asynchronous Demonstration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/styles.css" type="text/css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=The+Girl+Next+Door' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <script type="text/javascript" src="http://me.kis.scr.kaspersky-labs.com/1B74BD89-2A22-4B93-B451-1C9E1052A0EC/main.js" charset="UTF-8"></script></head>
  <body>
    <div class="demo">
      <div class="logo">
        NOT <img src="img/gmail_icon_small.png" width="25" height="15" alt="Gmail icon">
      </div>
      <div class="letter">
        <p>Dear friend,<p>
        <p>I am your long lost friend. I am trying to relate to my old friends.</p>
        <p>Please send me a reply!</p>
        <button type="submit" class="btn btn-default btn-success">
          Send 
          <span class="glyphicon glyphicon-repeat rotating"></span>
        </button>
      </div>
      <div id="retry" class="alert alert-warning">
        <span class="message">
          <strong>Having trouble in connecting...</strong> 
          Re-trying!! .. Attempt #<span class="timesSubmitted"></span>
        </span>
      </div>
      <div id="failed" class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <span class="message">
          <strong>Oh no!</strong> 
          We were not able to submit your information. Do you want to try again later?
        </span>
      </div>
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
    <script src="js/scripts.js"></script>
  </body>
</html> 

Following is the work flow diagram showing the execution flow.

Figure 3. Work flow diagram

Also, if you had looked into the Call Stack panel previously, there would be very little information on postonFail(). However, with the present version of DevTools, you can even go on to see if the request happened to be initiated by the submitHandler(), which happens on clicking the submit button, or the retrySubmit(), which occurs after a timeout.

Figure 4. Showing call stack

Asynchronously watching expressions

If you happen to walk through the entire call stack, the watch expressions also update and show the state that they happen to be in at a point of time.

The GIF given below will show you a little demonstration about how this can be seen.

Figure 5. Showing submit data

Evaluation of code from past scopes

With Chrome DevTools, it is not only possible to just observe and go through the updated state of your expressions, but also interact with the code from past scopes. This can be done in the JavaScript console panel in DevTools.

From the DevTools console, it is also possible for you to calculate, store or evaluate the values from the several execution points. Thus, staying with DevTools alone helps you from going back to your original source code, if you feel that there is a need to change certain parts of it, and then again refresh the browser.

Listing 2: Evaluating code

<!DOCTYPE html>
<html>
  <head>
    <title>Past Scope Async Demonstration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    body {
      text-align: left;
    }
    #tardis {
      cursor: pointer;
    }
    </style>
  </head>
  <body>
    <div class="demo">
      <!-- 
      <ol>
        <li>Open the DevTools</li>
        <li>Enable async call stacks</li>
        <li>Then refresh the page. DevTools automatically will kick in.</li>
        <li>Go back in time via the Call Stacks panel</li>
      </ol>
      -->
      <img src="tardis.jpg" width="350" height="350" alt="DrWho Tardis" id="tardis">
    </div>
    <script>
    var tard = document.getElementById('tardis'),
        timer = getTime(),
        who = "Outside the time machine @" + time;
    function startuptimemachine() {
      var timer = getTime(),
          who = "Inside the time machine @" + time;
      setTimeout(function travelThroughTime(){
        var timer = getTime(),
            who  = "Traveling through the time @" + time;
        debugger; // Stop right here if the DevTools is open
      }, 400);
      
    }
    function getTime(){ 
      return Date.now();
    }
    setTimeout(startuptimemachine, 900);
    </script>
  </body>
</html> 

Unraveling of chained promises

You must have seen how the previously provided mock Gmail was pretty hard to decipher without having the call stack async enabled. So imagine what the case would be with the likes of more complex flow, such as chained promises.

The call stack feature simple helps you track everything in such cases too, and it’s a whole lot easier for developers.

Getting insights from web animations

With async call stacks, one can get a lot of insight into requestAnimationFrame. Infact, it gives you the ability to go back all the way to the call back that initiates the scroll.

Observing mutations

The MutationObserver feature allows developers to observe changes that may come about in the DOM.

Listing 3: Sample showing mutation feature

<!DOCTYPE html>
<html>
  <head>
    <title>Demonstration for Mutation Observer</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      body {
        text-align: left;
      }
      .rows > div {
        background-color: #eee;
        margin: 8px 0;
        padding: 8px;
      }
    </style>
  </head>
  <body>
    <button onclick="addNode()">Click on the button to add a DOM node</button>
    <div class="rows">
    </div>
    <script>
      var rows = document.querySelector('.row'),
          rowindex = 0,
          observer;
      function nodeAdded(mutations) {
        console.log("rows.childNodes.length", rows.childNodes.length);
      }
      function addNode(){
        var row = document.createElement('div');
        row.classList.add('row');
        row.innerHTML = "Row " + (++rowIndex);
        rows.appendChild(row);
      }
      // create and init mutation observer
      observer = new WebKitMutationObserver(nodeAdded);
      observer.observe(rows, { childList: true });
    </script>
  </body>
  </html> 

In this piece of demonstration, every time you click on the add button, a new DOM is added. Now, if you add a breakpoint within nodeAdded() in say line 31, you can then walk the call stack right through the addNote() up to the click event that initiated it.

Conclusion

With the ability to see a full stack trace for your callbacks in JavaScript helps keep things simple and allows you to walk through and observe your code. This feature also particularly proves to be very insightful when there are multiple async events that happen with relation to another. Uncaught exceptions thrown from an async callback can also be detected with the help of DevTools.

The above tutorial gives you a great insight into how Chrome DevTools allows you to keep a track of your JavaScript callbacks with a few demonstrations. Although we have covered only about certain very basic features, you can also explore a lot more and how this feature proves to be very handy. As a developer, you should definitely give this new feature a try. We are sure that it would prove to be more than just useful and help you handle your callbacks in a better and organized manner.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login