Ben Aston
Ben Aston

Reputation: 55729

Is scope.$apply synchronous in AngularJS?

Is the following code synchronous in AngularJS?

scope.$apply(function(){
  console.log('foo');
});

Upvotes: 2

Views: 2401

Answers (5)

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

yes it is :

The angular source code is the following :

  $apply: function(expr) {
    try {
      beginPhase('$apply');
      try {
        return this.$eval(expr);
      } finally {
        clearPhase();
      }
    } catch (e) {
      $exceptionHandler(e);
    } finally {
      try {
        $rootScope.$digest();
      } catch (e) {
        $exceptionHandler(e);
        throw e;
      }
    }

and the function beginPhase :

function beginPhase(phase) {
  if ($rootScope.$$phase) {
    throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  }

  $rootScope.$$phase = phase;
}

Pay attention that it can throw an exception if there was currently a $apply or $digest in progress.

The applyAsync just pushes expressions into an array, that will be executed in the next $digest cycle.

If your aim is just to make sure there is no $digest in progress, you should do the following :

$timeout(
    scope.$apply(function(){
        console.log('foo');
    });
);

Which will be executed after the $digest cycle

Upvotes: 0

Alekos Filini
Alekos Filini

Reputation: 324

Since it seems to exist a $scope.$applyAsync() function, I would say that yes, this is a synchronous function.

Upvotes: 0

Mert Mertce
Mert Mertce

Reputation: 1634

$apply calls $eval.

And $eval is synchronous.

So, yes, $apply is.

For asnychronous, there is $evalAsync method.

Upvotes: 1

HaukurHaf
HaukurHaf

Reputation: 13796

Yes, it is.

$apply() is synchronous, and the browser blocks user input while JavaScript is running on the main thread. Should the user perform multiple input events quickly, the spec guarantees the browser will queue those events.

More here: https://github.com/angular/angular.js/issues/3782

Upvotes: 6

Tushar
Tushar

Reputation: 87203

Yes, $apply() is Synchronous.

IF you want Asynchronous counterpart, you can use

$applyAsync()

Schedule the invocation of $apply to occur at a later time. The actual time difference varies across browsers, but is typically around ~10 milliseconds.

This can be used to queue up multiple expressions which need to be evaluated in the same digest.

Also, read this thread.

Upvotes: 1

Related Questions