如何在angularjs中清除$timeout

kmpatx3s  于 2023-09-30  发布在  Angular
关注(0)|答案(3)|浏览(139)

我有这个图像滑块和下一个Prev和自动更改图像功能的代码

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);
});

在滑块模板中,我有下一个和上一个功能的箭头链接

<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>

我只是想添加清除$超时功能,当用户点击下一个或上一个btn,每次用户点击下一个或上一个btn的定时器是明确的,并在5秒后改变图像。
这是关于image slider的完整文档
我为此please look at this创建JSFiddle

jljoyd4f

jljoyd4f1#

这是我的第三次尝试: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);
};
f3temu5u

f3temu5u2#

你可以通过检查一个标志来设置$scope.next函数的超时。

标记

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

验证码

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

scope.next = function(setTimeoutToNext){
    scope.currentIndex < scope.images.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
    if(setTimeoutToNext)
      $timeout.cancel(timer); //here it will clear the timeout
}

Working Fiddle

a14dhokn

a14dhokn3#

嗨@Roman和@Pankaj坦克为巨大的帮助…使用此代码修复:

scope.next = function () {                 
            $interval.cancel(timer);
            scope.changeImage(); // just add this line
            timer = $interval(function () {
             scope.changeImage();
            }, 5000);                 
     };

this版本的@Roman编辑。
The Final version
坦克斯的家伙...

相关问题