https://www.cnblogs.com/imsomnus/p/7081033.html
Angular 定时器$timeout
和$interval
,延时调用
1. $timeout
用法如下:$timeout(fn,[delay],[invokeApply]);
fn
:一个将被延迟执行的函数。
delay
:延迟的时间(毫秒)。
invokeApply
:如果设置为false,则跳过脏值检测,否则将调用 $apply
。
具体使用:
本例是监听服务结合延迟方法执行
var timeout;
$scope.$watch('idNo', function(newVal, oldVal) {
if(newVal != oldVal) {
if(timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(function() {
$http.get(url).success(function(data) {});
}, 800);
}
});
2. $interval
用法如下:$interval(fn,delay,[count],[invokeApply],[Pass]);
fn
:一个将被反复执行的函数。
delay
:每次调用的间隔毫秒数值。
count
:循环次数的数值,如果没设置,则无限制循环。
invokeApply
:如果设置为false,则避开脏值检查,否则将调用$apply
。
Pass
:函数的附加参数。
- 实例:
function hello() {
...
console.log("hello world");
}
var timer = $interval(function(){
function hello() {}
},100);
timer.then(function() {
console.log("done");
});
复制代码
以上是每100毫秒执行hello()函数,每执行完一次则调用then函数。
2. 控制循环的次数:var timer =
i
n
t
e
r
v
a
l
(
f
u
n
c
t
i
o
n
(
)
,
100
,
10
)
;
,
参
数
10
则
是
限
制
定
时
器
循
环
10
次
,
若
该
参
数
没
有
定
义
则
表
示
无
数
次
循
环
。
3.
清
除
i
n
t
e
r
v
a
l
定
时
器
:
通
过
‘
i
n
t
e
r
v
a
l
.
c
a
n
c
l
e
(
t
i
m
e
r
)
‘
删
除
interval(function(){},100,10);,参数10则是限制定时器循环10次,若该参数没有定义则表示无数次循环。 3. 清除interval定时器:通过‘interval.cancle(timer)`删除
interval(function(),100,10);,参数10则是限制定时器循环10次,若该参数没有定义则表示无数次循环。3.清除interval定时器:通过‘interval.cancle(timer)‘删除interval返回的promise即可清除,而且必须要清除,否则会无限循环。在angular controller中只要开始执行定时任务,只要不清除则会一直执行,无论是否切换到其他的controller和页面,可能会导致不必要的错误。
4. 项目中用到的完整实例:
// 定时器 定时刷新数据
var timer = $interval(
function() {
hello();//自己定义的每次需要执行的函数,也可以写一些其他的内容
},
5000
);