AngularJS定时器的使用与移除操作方法【interval与timeout】

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

AngularJS定时器的使用与移除操作方法【interval与timeout】

小小小小小亮   2020-05-15 我要评论

本文实例讲述了AngularJS定时器的使用与移除操作方法。分享给大家供大家参考,具体如下:

1.相比较于JS中setTimeInterval和setTimeout,AngularJS中通过interval来实现定时器的效果,通过timeout来实现时间延迟。

$timeout //实现的是延迟执行
$interval //实现的是定时器的效果

我们分别来看这两个服务

(1)timeout

timeout相当于JS原生里面的延迟执行,不同的是该服务的函数返回的是一个promise对象。

var timer=$timeout(function(){
   console.log('hello world')
},2000);  //该函数延迟2秒执行
timer.then(function(){ console.log('创建成功')},
function(){ console.log('创建不成功')};

(2)interval

interval与timeout服务大同小异,创建定时器返回的也是一个promise对象。

var timer=$interval(function(){
   console.log('hello world')
},2000);  //间隔2秒定时执行
timer.then(function(){ console.log('创建成功')},
function(){ console.log('创建不成功')};

2.如何移除定时器

在angularJSo中,特别是在页面切换或者说是路由切换的时候,我们需要移除响应的定时器,我们可以通过on方法,监听路由切换时间。当DOM结构发生变化时,会执行on方法:

$scope.$on('destroy',function(){
  $interval.cancel($scope.timer);
}) //在控制器里,添加$on函数

希望本文所述对大家AngularJS程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们