Angular實現(xiàn)防抖和節(jié)流的示例代碼
更新時間:2024年02月20日 09:10:53 作者:crary,記憶
這篇博客主要是詳細介紹兩種常用Angular實現(xiàn)防抖和節(jié)流的方法:使用RxJS操作符和使用Angular自帶的工具,文中通過代碼示例給大家講解的非常詳細,需要的朋友可以參考下
在Angular中實現(xiàn)防抖和節(jié)流的方法有多種,這篇博客主要是詳細介紹兩種常用的方法:使用RxJS操作符和使用Angular自帶的工具。
- 使用RxJS操作符實現(xiàn)防抖和節(jié)流:
防抖(Debounce):
//簡易版
import { debounceTime } from 'rxjs/operators';
input.valueChanges.pipe(
debounceTime(300)
).subscribe(value => {
// 執(zhí)行搜索操作
});
//詳細版
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(() => {
// 執(zhí)行輸入框搜索操作
});
}
}- 節(jié)流(Throttle):
//簡易版
import { throttleTime } from 'rxjs/operators';
scrollEvent.pipe(
throttleTime(300)
).subscribe(() => {
// 執(zhí)行滾動操作
});
//詳細版
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(() => {
// 執(zhí)行滾動操作
});
}
}- 使用Angular自帶的工具實現(xiàn)防抖和節(jié)流:
- 防抖(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(() => {
// 執(zhí)行輸入框搜索操作
}, 300);
debounce(func, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
}
}- 節(jié)流(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(() => {
// 執(zhí)行滾動操作
}, 300);
throttle(func, delay) {
let canRun = true;
return function() {
if (!canRun) return;
canRun = false;
setTimeout(() => {
func.apply(this, arguments);
canRun = true;
}, delay);
};
}
}以上就是Angular實現(xiàn)防抖和節(jié)流的示例代碼的詳細內容,更多關于Angular防抖和節(jié)流的資料請關注腳本之家其它相關文章!
相關文章
Angular 4.x+Ionic3踩坑之Ionic3.x pop反向傳值詳解
這篇文章主要給大家介紹了關于Angular 4.x+Ionic3踩坑之Ionic3.x pop反向傳值的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-03-03
angular6.0開發(fā)教程之如何安裝angular6.0框架
這篇文章主要介紹了angular6.0開發(fā)教程之如何安裝angular6.0框架,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
AngularJS實現(xiàn)給動態(tài)生成的元素綁定事件的方法
這篇文章主要介紹了AngularJS實現(xiàn)給動態(tài)生成的元素綁定事件的方法,結合實例形式分析了AngularJS動態(tài)生成元素與事件綁定相關操作技巧,需要的朋友可以參考下2016-12-12

