RyanM RyanM - 3 months ago 13
AngularJS Question

AngularJS Wait for function with timeouts to complete before proceeding

I'm building a webapp using AngularJS, and trying to create a transition animation. When a button is pressed, the content is to fade out over 200ms, change to new content, and then fade back in again over 200ms. Below is the function called by ng-click on the button.



$scope.homeButton = function(){
fadeOut();
$scope.content="dolor sit amet";
fadeIn();
resetButtons();
$scope.homeButtonSrc = "res/homebuttonselected.png";
};





However, when the function is called, the content immediately changes, then fades out. Clicking on the button again toggles back and forth between the fading in and out animations. fadeIn() and fadeOut() are shown below.



var fadeOut = function fadeOut(){
var countDown = function(){
$scope.contentOpacity -= .01;
if($scope.contentOpacity > 0){
$timeout(countDown, 2);
}
}
$timeout(countDown, 2);
}
var fadeIn = function fadeIn(){
var countUp = function(){
$scope.contentOpacity += .01;
if($scope.contentOpacity < 1){
$timeout(countUp, 2);
}
}
$timeout(countUp, 2);
}





Any help would be appreciated!

Answer

You aren't using promises in your code, which are given by default by the $timeout function. Thus, your code is using an interval of only 2ms, and not 200ms.

Try to change your code like this:

$scope.homeButton = function(){
   fadeOut().then(function(){
      $scope.content="dolor sit amet";
      fadeIn().then(function(){
         resetButtons();
         $scope.homeButtonSrc = "res/homebuttonselected.png";
      });
   });
};

and your fadeIn() and fadeOut functions..

var fadeIn = function fadeIn(){
   var countUp = function(){
       $scope.contentOpacity += .01;
       if($scope.contentOpacity < 1){
           $timeout(countUp, 2);
       }
   }
   return $timeout(countUp, 200); //return here it's important
}
//same for fadeOut...

But the real answer here is to use ng-animate to perform your animations on angularjs. See the docs for more info about, i really suggest you to go this way.