Angular實現(xiàn)防抖和節(jié)流的示例代碼
在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é)流的示例代碼的詳細內(nèi)容,更多關(guān)于Angular防抖和節(jié)流的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Angularjs實現(xiàn)多圖片上傳預(yù)覽功能
這篇文章主要介紹了Angularjs實現(xiàn)多圖片上傳預(yù)覽功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
詳解angular中通過$location獲取路徑(參數(shù))的寫法
本篇文章主要介紹了詳解angular中通過$location獲取路徑(參數(shù))的寫法 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03
Angular中使用ng-zorro圖標庫部分圖標不能正常顯示問題
這篇文章主要介紹了Angular中使用ng-zorro圖標庫部分圖標不能正常顯示問題,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04
AngularJS實現(xiàn)表單手動驗證和表單自動驗證
本文是對AngularJS表單驗證,手動驗證或自動驗證的講解,對學(xué)習(xí)JavaScript編程技術(shù)有所幫助,感興趣的小伙伴們可以參考一下2015-12-12
Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output詳解(下)
這篇文章主要給大家介紹了關(guān)于Angular 2父子組件數(shù)據(jù)傳遞之@Input和@Output的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-07-07

