javascript - 如何清除angularjs中的$timeout

标签 javascript angularjs asynchronous timeout angularjs-timeout

我有这个代码用于图像 slider 和下一个上一个以及自动更改图像功能

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

在 slider 模板中,我有下一个和上一个函数的箭头链接

  <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 时添加清除 $timeout 功能,每次用户点击下一个或上一个 btn 时,计时器都会清除并在 5 秒后更改图像。

这是关于 image slider 的完整文档

我为此 please look at this 创建了 JSFiddle

最佳答案

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

希望对你有帮助。

关于javascript - 如何清除angularjs中的$timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31981292/

相关文章:

javascript - ng-repeat 的问题

ruby - Ruby 中的高负载 RESTful API(同步/异步实现)

c# - 用于具有复杂后台计算的响应式 GUI 的多线程 C# - 异步/等待、TPL 或两者?

javascript - ajax内访问父对象的 `this`变量

javascript - BrowserStack 自动化测试 - 单击操作在 Android 上不起作用

AngularJS 如何获取额外的路由参数

javascript - $ionicLoading 中的可点击内容

javascript - 类型错误 : Cannot read property 'data' of undefined - can't access Object "props" beyond certain level in Reactjs

javascript - Chart.js不会在IE中显示图表

javascript - 如何显示从 javascript 到 php 的脚本值