Why using AngularJs’s global objects instead of native ?

Timeout case

setTimeout is part of the window object, helpful to execute a function or evaluating an expression one time after a certain delay in milliseconds.

Let’s setting up a basic AngularJS application with a controller:

In this example, after 2 seconds the firstMessage will be updated but the secondMessage not, as shown on the following page:

setTimeout:

Here is invoked with two parameters, the function we would like to call and the delay for it to happen.

When we are using it into an AngularJs application we also need to apply the eventual scope changes to the angular digest, because the default timeout runs outside of the AngularJs life-cycle that also means our bi-directional binding will not render the update.

That is why it’s needed here to refresh the AngularJs scope with the call of $rootScope.$apply() or $rootScope.$applyAsync().

$apply and $applyAsync serve the same purpose but with a delay difference on the second one.

$timeout:

Almost the same syntax as the previous but there are more parameters here that can be pass to its call.

For example, we can also decide to call it outside of the life cycle:

$timeout(function() {
    $scope.firstMessage = 'First message updated';
    alert($scope.firstMessage);
}, 2000, false);

Here we see that one more parameter can be added to this service, it’s a boolean to say if yes or no we want the apply to follow our function call after 2 seconds.

In simple word, call it with false as the third parameters will call our function outside of AngularJS framework.

Note: By default this third parameter is true.

The documentation stated it clearly here.

read original article here