如何在路由更改后停止 setInterval 函数在角度指令上执行

How to stop a setInterval function from executing on an angular directive after route change

本文关键字:函数 执行 setInterval 指令 路由      更新时间:2023-09-26

我通过指令将图库放入页面中。 该图库使用 javascript 在图像之间来回解析(我计划使用 css 过渡在类数组中旋转)。

我希望执行一个setInterval函数,但仅当指令在页面上时(也就是说,仅在调用某个路由时)。但是,即使命中新路由,并且在我的页面上呈现了新视图,现有函数仍在执行。 例如:

命令:

angular.module('app')
  .directive('gallery', function ($location) {
    return function (scope, element, attrs) {
      setInterval(function () {
        //This is where I would change the classes on the element
        //This will continually execute, even when on a different view
      }, 500);
    }
  });

网页视图

<div gallery>
    Something special
</div>

有什么方法可以只在指令在页面上时执行间隔函数?

您可以取消$destroy事件的间隔。

var intervalPromise = $interval(function() {
  // do your operation
}, 500);
element.on('$destroy', function() {
   $interval.cancel(intervalPromise);
});

以下是文档的链接:https://docs.angularjs.org/guide/directive

你应该

使用$interval:-

    var promise=$interval(function () {
    }, 500);
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        if(next!=current)
            $interval.cancel(promise);
    });

或者如果您使用的是 setInterval:-

var promise=setInterval(function () {
      }, 500);
$rootScope.$on("$locationChangeStart", function(event, next, current) { 
        if(next!=current)
           clearInterval(promise);
    });