Liem
Liem

Reputation: 770

Need to use $timeout and $apply with requestAnimationFrame

I am trying to create a JavaScript animation with a rolling number using requestAnimationFrame.

In order to see the see the animation rolling, I need to use a $apply to refresh the view. The problem here is when I start the animation, the digest cycle is already running so my $apply returns an error "$apply already in progress".

Looking for a solution I use a $timeout of 0, which works perfectly, but I was wondering if there was other solution to avoid using a timeout that is not really good in terms of performance?

Html Code:

<div ng-app="myApp">
  <div ng-controller="myController as ctrl">
    <animated-counter data-from='0' data-to='{{ctrl.limit}}'></animated-counter>
  </div>
</div>

Javascript Code:

(function(){
'use strict';

angular
    .module('myApp', [])
    .directive('animatedCounter', AnimatedCounter);

    AnimatedCounter.$inject = ['$timeout'];

    function AnimatedCounter($timeout) {
        return {
            restrict: 'E',
            template: '<div>{{num}}%</div>',
            link: function (scope, element, attrs) {
                scope.num = parseInt(attrs.from);
                var max = parseInt(attrs.to);

                //Loop to increment the num
                function animloop() {
                    if (scope.num >= max) { //Stop recursive when max reach
                        return;
                    }
                    requestAnimationFrame(animloop);
                    scope.$apply(function() {
                        scope.num += 1;
                    });
                }
              
                // $timeout(function() { //if I use $timeout it works perfectly
                    animloop();
                // });
            }
        };
    }


 angular
    .module('myApp')
    .controller('myController', myController);

    function myController() {
       var vm = this;
       vm.limit = 100;
    }
})();

You can find here a CodePen

http://codepen.io/phliem/pen/ZWOjwz?editors=1011

Upvotes: 3

Views: 1563

Answers (1)

Liem
Liem

Reputation: 770

Working great if I use $evalAsync() as HadiJZ said!

just need to replace

scope.$apply(function() {
   scope.num += 1;
});

by

scope.$evalAsync(function() {
   scope.num += 1;
})

There is a good article here http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm

Upvotes: 5

Related Questions