在此用例中,$ interval和$ timeout之间是否有真正的区别? [英] Is there a real difference between $interval and $timeout in this use case?
本文介绍了在此用例中,$ interval和$ timeout之间是否有真正的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
两者之间是否存在真正的区别
Is there a real difference between:
$interval(function () {
doSomething();
}, 250, 1, true);
和
$timeout(function () {
doSomething();
}, 250);
- 两个回报承诺
- 两个都执行一次
doSomething()
一次. - 两者都触发摘要循环.
我可能注意到的唯一可能的区别是,如果对 $ interval
的最后一个参数使用 false
,则可以绕过摘要循环.
The only possible difference I could notice is that I could bypass a digest cycle if I use false
for the last parameter of $interval
.
推荐答案
让我们做一些代码分析
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
finally {
delete deferreds[promise.$$timeoutId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
return promise;
}
间隔
function interval(fn, delay, count, invokeApply) {
var setInterval = $window.setInterval,
clearInterval = $window.clearInterval,
deferred = $q.defer(),
promise = deferred.promise,
iteration = 0,
skipApply = (isDefined(invokeApply) && !invokeApply);
count = isDefined(count) ? count : 0;
promise.then(null, null, fn);
promise.$$intervalId = setInterval(function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
deferred.resolve(iteration);
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
intervals[promise.$$intervalId] = deferred;
return promise;
}
最后的区别是不正确的,因为这两种方法都实现了 if(!skipApply)$ rootScope.$ apply();
没有没有区别.
Last difference is not true as both of methods implements if (!skipApply) $rootScope.$apply();
There is no difference.
这篇关于在此用例中,$ interval和$ timeout之间是否有真正的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文