如何在路由更改后停止 setInterval 函数在角度指令上执行
How to stop a setInterval function from executing on an angular directive after route change
我通过指令将图库放入页面中。 该图库使用 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);
});
相关文章:
- 等待回调函数执行
- 暂停函数执行流程,直到ajax请求完成
- Bigcommerce-是否可以在函数执行后更改文本
- 如何对jquery中的未命名函数执行.call()
- 等待函数执行后再继续
- mootools类型的函数将文本作为函数执行
- 停止从另一个函数执行Javascript函数
- Jquery回调函数执行多次
- 如何使即兴 jquery 暂停当前函数执行
- JavaScript 双函数执行
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 如何在 JS 中调用 2 次或更多次时延迟函数执行
- 函数执行的次数超出预期
- JS中函数执行错误
- 为什么这个函数执行了两次
- 从子函数执行父函数;t更新父级'的属性
- 如何在jQuery函数执行's处于活动状态
- 使用javascript函数执行php文件
- jQuery函数执行顺序
- javascript中同步函数执行中的问题