Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can clear $timeout in angularjs

I have this code for image slider and next prev and auto change the image function

scope.next = function () {
    scope.currentIndex < scope.images.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
};

scope.prev = function () {
    scope.currentIndex > 0 ? scope.currentIndex-- : scope.currentIndex = scope.images.length - 1;
};

scope.$watch('currentIndex', function () {
    scope.images.forEach(function (image) {
    image.visible = false;
    });

    scope.images[scope.currentIndex].visible = true;
});

var timer;
var sliderFunc = function () {
    timer = $timeout(function () {
        scope.next();
        timer = $timeout(sliderFunc, 5000);
    }, 5000);
};

sliderFunc();

scope.$on('$destroy', function () {
    $timeout.cancel(timer);
});

and in slider template I have the arrows link for next and prev function

  <div class="arrows">
    <a href="#" ng-click="prev()">
      <img src="tasavir/omgh/left-arrow.png" />
    </a>
    <a href="#" ng-click="next()">
      <img src="tasavir/omgh/right-arrow.png" />
    </a>
  </div>

I just want to add clear $timeout function when user click on the next or prev btn and each time the user click on the next or prev btn the timer was clear and change image in 5s later.

this is the full doc about image slider

I create the JSFiddle for this please look at this

like image 700
Syd Amir Avatar asked Jun 04 '26 14:06

Syd Amir


1 Answers

This is my third try: https://jsfiddle.net/koljada/8cLw6wch/22/

var timer = $interval(function () {
    scope.changeImage();
}, 5000);

scope.next = function () {
    $interval.cancel(timer);

    timer = $interval(function () {
        scope.changeImage();
    }, 5000);
};

scope.changeImage = function () {
    scope.currentIndex < scope.images.length - 1
        ? scope.currentIndex++
        : (scope.currentIndex = 0);
};
like image 78
Roman Koliada Avatar answered Jun 07 '26 07:06

Roman Koliada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!