difference between setTimeout in javascript and $timeout service in angularjs difference between setTimeout in javascript and $timeout service in angularjs angularjs angularjs

difference between setTimeout in javascript and $timeout service in angularjs


There are some cases where one needs to perform some sort of timeout operation and we frequently achieve this using JavaScript's setTimeout() function.

However, if we use setTimeout() in an AngularJS application we also need to use $scope.$apply() to ensure that any changes to the scope will be reflected elsewhere (i.e. data-bound in a view).

AngularJS provides a handy wrapper for this: $timeout() - it does the $apply() for which we don't have to $apply the changes.

Regarding the performance.

If you're using $timeout to create what is essentially an interval, then don't use it. If your application is large then $apply will also trigger a $digest cycle which you may not really want it to happen, it will surely decrease the performance.


Any AngularJS scope variable when handled from outside (including ajax) needs a $apply().

$timeout() takes care of the current scope and runs in the same digest cycle after all the change detection is done.

One beauty of $timeout() that I recently discovered is, if you do not pass the time parameter, it will wait for the DOM completion.

So,

$timeout(function(){  console.log("show after directive partial loaded")}); //note, no time parameter

Run this code in a directive and the timeout callback function will be fired once the partial has been loaded by the directive

Hope this helps.