AngularJS中的定时器,以及定时器的移除

来源:互联网 发布:2016星火英语听力软件 编辑:程序博客网 时间:2024/06/05 10:11

1.相比较于JS中setTimeInterval和setTimeout,angularJS中通过intervaltimeout来实现时间延迟。

$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中,特别是在页面切换或者说是路由切换的时候,我们需要移除响应的定时器,我们可以通过onDOMon方法:

$scope.$on('destroy',function(){   $interval.cancel($scope.timer);})  //在控制器里,添加$on函数
0 0
原创粉丝点击