Diane Duquesne
Diane Duquesne

Reputation: 514

Execute a function for specific amout of time - AngularJs

I would like to animate a input slider when the user arrived at this div. To watch if the user scrolled to this div I am using a directive, which triggered the change of value of my slider. Here is the code :

directive("scroll", function ($window, $timeout, $interval) {
          return function(scope, element, attrs) {
              angular.element($window).bind("scroll", function() {
                   if (this.pageYOffset >= 1500) {
                     var timeout = $timeout(function(){
                          var interval = $interval(function(){
                            scope.slider += 4;
                          },25);
                      }, 0);
              });
          };
      })

This work well, increasing the value smoothly, with a nice animation effect however this doesn't stop increasing. I tried to add :

                      var second_timeout = $timeout(function(){
                        scope.slider= 400;
                      }, 100)

To fix a value, but it "jumped" and then continues to increase.

I also tried to add a while loop to avoid the slider's value to be higher than 500, this worked but there's no more "Animation" effect.

I chose this way of doing it, which may appear complicated because I didn't find any way to make it with CSS animations.

Does a pure angularJs function exist to specify an amount of time during which a function should be executed?

Thank you for your answers!

Upvotes: 1

Views: 48

Answers (1)

Ignacio Villaverde
Ignacio Villaverde

Reputation: 1264

You are defining an interval. That function will continue running and that is why it does not stop.

You could do something like this:

var timesRun = 0;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 60){
        clearInterval(interval);
    }
    scope.slider += 4; 
}, 25); 

Upvotes: 1

Related Questions