Difference between $interval and setInterval in AngularJs

后端 未结 2 907
说谎
说谎 2021-01-02 22:09

I\'m trying to understand what\'s the difference between $interval and setInterval. I have this test:

Dashboard.prototype.updateTotalAppointments = function(         


        
相关标签:
2条回答
  • 2021-01-02 22:47

    $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

    0 讨论(0)
  • 2021-01-02 22:48

    $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);
        };
      });
    
    0 讨论(0)
提交回复
热议问题