Angular 5 中 $interval
AngularJS $interval
是一种以固定时间间隔执行函数的方法。在 Angular 5 中,RxJS
库中有一个计时器静态方法,可以用来做同样的事情。
静态计时器方法有两个参数。第一个是以毫秒为单位的间隔,第二个是在此间隔过去时调用的可选函数。
当可观察序列完成时,take 运算符可用于取消任何挂起的计时器。让我们首先详细讨论 $interval
方法,然后我们将转到 Angular 中的计时器静态方法
和 take operator
。
AngularJS 中的 $interval
服务
AngularJS 中的 $interval
服务与 JavaScript 中的 setInterval()
方法做同样的事情。 $interval 变量是 setInterval()
方法的包装器,可以很容易地更改、删除或模拟以进行测试。
setInterval
函数以毫秒为间隔重复执行给定函数,只要它至少被调用一次。
第一次调用 setInterval
将立即执行给定的函数,然后每隔指定的毫秒数执行间隔对象本身的 clearInterval
。
例子:
let timer = setInterval(() => alert('start'), 1000);
// after 20 seconds
setTimeout(() => { clearInterval(timer); alert('stop'); }, 10000);
在 Angular 5 中使用静态时间和 Take
方法
静态时间是 Angular 5 中的一项新功能,它允许开发人员为其应用程序的数据设置时区。这可以在运行时通过将时区的值传递给 Static Time
服务或选择它作为应用程序配置参数来完成。
添加此功能以允许开发人员使用 Angular 5 处理来自不同时区的数据,而无需手动转换数据字符串。Take
方法是另一个新功能,它允许开发人员指定特定操作在中止之前需要多长时间,如果它需要更长的时间。
示例代码:
import { Component, VERSION } from '@angular/core';
import { Observable, timer } from 'rxjs';
import { map, take } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
counter$: Observable<number>;
count = 5;
ngOnInit() {
this.counter$ = timer(0, 5000)
.pipe(
take(5),
map(() => (this.count))
);
this.counter$.subscribe((c) => {
console.log(c);
}, () => {}, () => {
console.log('Done', this.count);
});
}
}
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。