![]()
$timeoutand$intervalare AngularJS services used for delayed execution and repeated execution, respectively.- Internally, both are wrappers around JavaScript’s
setTimeoutandsetInterval, 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): Iftrue(default), it triggers$digestautomatically.
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$digestcycle.
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): Iftrue(default), triggers$digestautomatically.
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?
- Both use JavaScript’s
setTimeout()andsetInterval() - Wrapped inside AngularJS’s
$rootScope.$applyAsync() - Ensures changes trigger a digest cycle
- Automatically cleaned up when the scope is destroyed
Key Differences: $timeout vs $interval
| Feature | $timeout | $interval |
|---|---|---|
| Function | Delays execution once | Repeats execution at intervals |
| JavaScript Equivalent | setTimeout() | setInterval() |
Auto $digest | Yes | Yes |
| Can Be Canceled | Yes ($timeout.cancel()) | Yes ($interval.cancel()) |
| Stops Automatically | Yes (runs once) | No (must be stopped manually) |
