Angular实现防抖和节流的示例代码
更新时间:2024年02月20日 09:10:53 作者:crary,记忆
这篇博客主要是详细介绍两种常用Angular实现防抖和节流的方法:使用RxJS操作符和使用Angular自带的工具,文中通过代码示例给大家讲解的非常详细,需要的朋友可以参考下
在Angular中实现防抖和节流的方法有多种,这篇博客主要是详细介绍两种常用的方法:使用RxJS操作符和使用Angular自带的工具。
- 使用RxJS操作符实现防抖和节流:
防抖(Debounce):
//简易版
import { debounceTime } from 'rxjs/operators';
input.valueChanges.pipe(
debounceTime(300)
).subscribe(value => {
// 执行搜索操作
});
//详细版
import { Component } from '@angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-debounce-example',
template: '<input (input)="onInput($event)">'
})
export class DebounceExampleComponent {
onInput(event: Event) {
fromEvent(event.target, 'input')
.pipe(
debounceTime(300)
)
.subscribe(() => {
// 执行输入框搜索操作
});
}
}- 节流(Throttle):
//简易版
import { throttleTime } from 'rxjs/operators';
scrollEvent.pipe(
throttleTime(300)
).subscribe(() => {
// 执行滚动操作
});
//详细版
import { Component } from '@angular/core';
import { fromEvent } from 'rxjs';
import { throttleTime } from 'rxjs/operators';
@Component({
selector: 'app-throttle-example',
template: '<div (scroll)="onScroll($event)">'
})
export class ThrottleExampleComponent {
onScroll(event: Event) {
fromEvent(event.target, 'scroll')
.pipe(
throttleTime(300)
)
.subscribe(() => {
// 执行滚动操作
});
}
}- 使用Angular自带的工具实现防抖和节流:
- 防抖(Debounce):
import { Component } from '@angular/core';
@Component({
selector: 'app-debounce-example',
template: '<input (input)="onInput($event)">'
})
export class DebounceExampleComponent {
onInput(event: Event) {
this.debounceSearch();
}
debounceSearch = this.debounce(() => {
// 执行输入框搜索操作
}, 300);
debounce(func, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
}
}- 节流(Throttle):
import { Component } from '@angular/core';
@Component({
selector: 'app-throttle-example',
template: '<div (scroll)="onScroll($event)">'
})
export class ThrottleExampleComponent {
onScroll(event: Event) {
this.throttleScroll();
}
throttleScroll = this.throttle(() => {
// 执行滚动操作
}, 300);
throttle(func, delay) {
let canRun = true;
return function() {
if (!canRun) return;
canRun = false;
setTimeout(() => {
func.apply(this, arguments);
canRun = true;
}, delay);
};
}
}以上就是Angular实现防抖和节流的示例代码的详细内容,更多关于Angular防抖和节流的资料请关注脚本之家其它相关文章!
相关文章
详解angular中通过$location获取路径(参数)的写法
本篇文章主要介绍了详解angular中通过$location获取路径(参数)的写法 ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2017-03-03
Angular中使用ng-zorro图标库部分图标不能正常显示问题
这篇文章主要介绍了Angular中使用ng-zorro图标库部分图标不能正常显示问题,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下2019-04-04
Angular 2父子组件数据传递之@Input和@Output详解(下)
这篇文章主要给大家介绍了关于Angular 2父子组件数据传递之@Input和@Output的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。2017-07-07


最新评论