AngularJS When processing the DOM takes a long time

You already know that you can add a progress spinner when an asynchronous process takes a long time. For example, say you’re loading data from a REST call.

$http.get(url)
  .then(function(res) {
    $scope.data = res.data;
  });

<div ng-hide="data">
  <i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
</div>

<div ng-show="data">
  {{data}}
</div>

But let’s say you need to reload that data, like paging. And suppose the data is HUGE and it takes a really long time for the DOM to be updated even if you already have the data in memory. What happens is that when you initiate action, the page seems to stall with the old data still there. This is bad UI because it makes the user feel like nothing is happening and may cause them to click around.

Ideally, you want the old data to be cleared so that the spinner can appear again. But clearing the data before setting it won’t do what you’d expect.

function() {
  $scope.data = null;
  $scope.data = ...
}

What happens here is that $scope.data is set to null, then to the new data, but the page will not change until the new data is painted and ready to show to the user. Why didn’t setting $scope.data to null immediately make the spinner appear?

Angularjs only sees the changes at the end of the function. Form Angular’s view, $scope.data went from the old data to the new. It never saw the update to null.

Here’s how I get around that.

function() {
  $scope.data = null;

  setTimeout(function() {
    $scope.$apply(function() {
      $scope.data = ...
    })
  }, 100)
}

In the main thread of the code, I set $scope.data to null. Then I create a 2nd thread with the setTimeout() which is asynchronous, so the function ends and angularjs updates. It now sees that $scope.data is null so it erases the DOM and shows the spinner.

Eventually, the timer kicks off (set for 100ms in this case), and it applies the function that sets $scope.data to the new data. While this is happening and the DOM is painted in the background, the user sees the spinning icon. Once it’s complete, the spinner goes away and the data is shown.

Advertisements
Tagged

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: