5

I have a single page application using AngularJS and I am facing one performance issue in it. My application processes incoming events from the server side which are passed to the AngularJS framework on the client side using ASP.NET SignalR. There are millions of events that can be received by my application and there is no performance issue on the server side and it easily passes these number of events one after the other to the AngularJS framework. The problem lies on the client side. After processing the event, i use $scope.$apply() to update the page and display the events. In such a case where there are multiple events being received one after the other, calling $scope.$apply() every time slows down the application and does not show the events quickly. The events will be passed at random so I don't even know how any events will be received by my application at any point in time.

Any ideas on how to get this issue resolved will be very helpful.

Thanks.

Shish
  • 61
  • 2

1 Answers1

5

Instead of using $scope.$apply(), use $scope.$evalAsync() instead.

From the docs:

Executes the expression on the current scope at a later point in time.

The $evalAsync makes no guarantees as to when the expression will be executed, only that:

  • it will execute after the function that scheduled the evaluation (preferably before DOM rendering).
  • at least one $digest cycle will be performed after expression execution.

Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.

Note: if this function is called outside of a $digest cycle, a new $digest cycle will be scheduled. However, it is encouraged to always call code that changes the model from within an $apply call. That includes code evaluated via $evalAsync.

I also tended to have a $scope.$safeApply() method as well that was effectively a debounced call to $scope.$evalAsync().

GregL
  • 37,147
  • 8
  • 62
  • 67