I'm trying to understand what's the difference between $interval and setInterval. I have this test:
Dashboard.prototype.updateTotalAppointments = function(){
//console.log();
this.appointmentsCount = this.appointmentsCount +1;
console.log(this.appointmentsCount);
};
Dashboard.prototype.start = function(){
setInterval(function(){
this.updateTotalAppointments();
}.bind(this), 3000);
}
>
div class="hb-info-card-data-count"><h1>{{dashCtrl.appointmentsCount}}</h1></div>
Using setInterval doesn't update the value on the HTML page, but the value actually changes on the browser console, but it just doesn't get updated on the Html page.
but if i do this :
Dashboard.prototype.start = function(){
$interval(function(){//using $interval seems to work fine
this.updateTotalAppointments();
}.bind(this), 3000);
}
This seems to work perfectly, so i really don't know why the latter didn't work, but i would really like to know please.
And also what will be the best way to constantly request data from the background lets say every n-minutes and update the page via its controller.
$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);
};
});
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With