I\'m trying to understand what\'s the difference between $interval and setInterval. I have this test:
Dashboard.prototype.updateTotalAppointments = function(
$interval is a wrap for setInterval AND $apply simultaneous. It make the update of scoped variables to be visible when occours on $interval. Also valid for $timeout
$interval is Angular's wrapper for the native Javascript setInterval.
When $interval
is used, Angular is aware of any scope changes made by the interval function, and the two-way binding reflects the changes.
When setInterval
is used, Angular will not be aware of any scope changes made by the setInterval function.
Put simply, the $interval
function triggers Angular's digest cycle while setInterval
does not.
This plunkr demonstrates the difference.
Code:
angular.module('DemoApp', [])
.controller('IntervalCtrl', function($scope, $interval) {
var updateExampleText = function() {
console.log('Changing exampleText');
$scope.exampleText = 'Time: ' + new Date().getSeconds();
};
$scope.useInterval = function() {
//Show current seconds value 5 times after every 1000 ms
$interval(updateExampleText, 1000, 5);
};
$scope.useSetInterval = function() {
//$scope.exampleText changes are not reflected in the page
//because Angular is not aware of the changes.
setInterval(updateExampleText, 1000);
};
});