AngularJS provides two built-in services, $timeout
and $interval
, for handling asynchronous operations similar to JavaScript’s setTimeout()
and setInterval()
. However, they integrate seamlessly with AngularJS’s digest cycle, ensuring updates are reflected in the UI.
- $timeout: Executes a function once after a specified delay.
- $interval: Executes a function repeatedly at a fixed time interval.
When used inside services, these can be helpful for delayed execution, polling data, auto-refreshing UI, and performance optimizations.
1. Understanding $timeout
Use Case: Delayed Execution Inside a Service
$timeout
is useful when you need to delay execution of a function inside a service.
Example: Creating a Notification Service with $timeout
app.factory('NotificationService', function($timeout) {
var notifications = [];
return {
addNotification: function(message, duration) {
var notification = { message: message };
notifications.push(notification);
// Remove notification after a set time
$timeout(function() {
var index = notifications.indexOf(notification);
if (index !== -1) {
notifications.splice(index, 1);
}
}, duration);
},
getNotifications: function() {
return notifications;
}
};
});
How It Works?
addNotification()
adds a message to the notifications list.$timeout
removes the notification afterduration
milliseconds.
Use $timeout
when you need a one-time delay inside a service.
2. Understanding $interval
Use Case: Polling API Data Inside a Service
$interval
is useful when you need to execute a function repeatedly, such as polling an API at regular intervals.
Example: Fetching Data Every 5 Seconds Using $interval
app.factory('DataPollingService', function($http, $interval) {
var data = [];
function fetchData() {
$http.get('/api/data').then(function(response) {
data = response.data;
});
}
// Start polling every 5 seconds
var polling = $interval(fetchData, 5000);
return {
getData: function() {
return data;
},
stopPolling: function() {
$interval.cancel(polling);
}
};
});
How It Works?
fetchData()
fetches data from the API every 5 seconds.$interval(fetchData, 5000)
ensures the API is called repeatedly.stopPolling()
cancels polling when needed.
Use $interval
when you need periodic execution inside a service.
3. $timeout
vs $interval
– Key Differences
Feature | $timeout | $interval |
---|---|---|
Execution Type | One-time delay | Repeated execution |
Use Case | Delayed actions | Polling, auto-refreshing UI |
Cancellation | $timeout.cancel() | $interval.cancel() |
Performance Impact | Minimal | Can impact performance if not cleared |
4. Canceling $timeout
and $interval
to Prevent Memory Leaks
Cancelling $timeout
var timer = $timeout(function() {
console.log("Executed after delay");
}, 3000);
// Cancel timeout if needed
$timeout.cancel(timer);
Cancelling $interval
var intervalTask = $interval(function() {
console.log("Repeating every 5 sec");
}, 5000);
// Stop execution when not needed
$interval.cancel(intervalTask);
Always cancel $timeout
and $interval
in controllers or services to prevent memory leaks!
5. Choosing Between $timeout
and $interval
Scenario | Use $timeout | Use $interval |
---|---|---|
Displaying a message for a few seconds | ✅ | ❌ |
Delaying function execution | ✅ | ❌ |
Polling data from an API | ❌ | ✅ |
Running a function repeatedly | ❌ | ✅ |
Auto-refreshing UI elements | ❌ | ✅ |