3

I've built a very simply slider with Angular like so:

$scope.slider = {};
$scope.slider.pane = 1;
$scope.slider.auto = true;

var slider = function(){
  $timeout(function(){
    if ($scope.slider.pane === 4) $scope.slider.pane = 1;
    else $scope.slider.pane ++;
    slider();
  }, 4000);
}
slider();

The slider function creates a timeout loop to change the value of slider.pane every 4s. In the HTML I have a link that when clicked sets the value slider.auto to false.

<a href="" ng-click="slider.auto=false">Stop slider</a>

When this is clicked, it needs to stop the timeout loop. It may be in the middle of a cycle at the time, so I need to clear the timeout, but it's inside a function so not sure how to access it.

CaribouCode
  • 13,998
  • 28
  • 102
  • 174

3 Answers3

4

Use the $timeout.cancel function:

var timeout;
$scope.cancelTimer = function() {
    $scope.slider.auto=false;
    $timeout.cancel(timeout);
};

var slider = function(){
  timeout = $timeout(function(){
    if ($scope.slider.pane === 4) $scope.slider.pane = 1;
    else $scope.slider.pane ++;
    slider();
  }, 4000);
}
slider();

//HTML
<a href="" ng-click="cancelTimer()">Stop slider</a>
eladcon
  • 5,815
  • 1
  • 16
  • 19
0

Try:

$scope.slider = {};
$scope.slider.pane = 1;
$scope.slider.auto = true;
var promise;
var slider = function(){
  promise = $timeout(function(){
    if ($scope.slider.pane === 4) $scope.slider.pane = 1;
    else $scope.slider.pane ++;
    slider();
  }, 4000);
}
$scope.autoSliderFalse = function() {
    $scope.slider.auto = false;
    if(promise)
       $timeout.cancel(promise);
});
slider();

HTML

<a href="" ng-click="autoSliderFalse()">Stop slider</a>
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
0

You can use the cancel method as some people suggested here.

I actually think in your case you should use $interval instead of $timeout.

var interval = $interval(function(){
  if ($scope.slider.pane === 4) {
    $scope.slider.pane = 1;
  }
  else {
    $scope.slider.pane ++;
  }    
}, 4000);

$scope.stopSlider = function(){
  $interval.cancel(interval);
};

//html
<a href="" ng-click="stopSlider()">Stop slider</a>
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59