Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $interval and setInterval in AngularJs

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.

like image 618
Paul Okeke Avatar asked Aug 08 '15 03:08

Paul Okeke


2 Answers

$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);
    };
  });
like image 122
WeNeigh Avatar answered Oct 30 '22 20:10

WeNeigh


$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

like image 35
Joao Polo Avatar answered Oct 30 '22 21:10

Joao Polo