How $timeout and $interval work internally?

Loading

  • $timeout and $interval are AngularJS services used for delayed execution and repeated execution, respectively.
  • Internally, both are wrappers around JavaScript’s setTimeout and setInterval, but with AngularJS digest cycle integration.

1. $timeout – Delayed Execution

  • Similar to JavaScript’s setTimeout(), but ensures AngularJS detects changes and triggers a digest cycle.

Syntax

$timeout(function () {
// Code to execute after delay
}, delay, invokeApply);
  • delay: Time in milliseconds before execution.
  • invokeApply (optional): If true (default), it triggers $digest automatically.

Example

var app = angular.module("myApp", []);

app.controller("MainController", function ($scope, $timeout) {
$scope.message = "Before timeout";

$timeout(function () {
$scope.message = "Updated after timeout!";
}, 2000);
});

Automatically updates the UI after 2 seconds because $timeout triggers $digest.


2. $interval – Repeated Execution

  • Works like JavaScript’s setInterval(), but integrates with AngularJS’s $digest cycle.

Syntax

var intervalPromise = $interval(function () {
// Code to execute repeatedly
}, interval, count, invokeApply);
  • interval: Time between executions in milliseconds.
  • count (optional): Number of times to execute before stopping.
  • invokeApply (optional): If true (default), triggers $digest automatically.

Example

var app = angular.module("myApp", []);

app.controller("MainController", function ($scope, $interval) {
$scope.counter = 0;

var intervalPromise = $interval(function () {
$scope.counter++;
}, 1000, 5); // Runs 5 times

$scope.stopInterval = function () {
$interval.cancel(intervalPromise);
};
});

Counter increases every second for 5 times.
Can be manually stopped using $interval.cancel().


How $timeout and $interval Work Internally?

  1. Both use JavaScript’s setTimeout() and setInterval()
  2. Wrapped inside AngularJS’s $rootScope.$applyAsync()
  3. Ensures changes trigger a digest cycle
  4. Automatically cleaned up when the scope is destroyed

Key Differences: $timeout vs $interval

Feature$timeout$interval
FunctionDelays execution onceRepeats execution at intervals
JavaScript EquivalentsetTimeout()setInterval()
Auto $digest Yes Yes
Can Be Canceled Yes ($timeout.cancel()) Yes ($interval.cancel())
Stops Automatically Yes (runs once) No (must be stopped manually)

Leave a Reply

Your email address will not be published. Required fields are marked *