当前位置:   article > 正文

Angular中如何实现防抖和节流_angular防抖和节流的处理

angular防抖和节流的处理

        在Angular中实现防抖和节流的方法有多种,这篇博客主要是详细介绍两种常用的方法:使用RxJS操作符和使用Angular自带的工具。

  1. 使用RxJS操作符实现防抖和节流:

     防抖(Debounce):

    1. //简易版
    2. import { debounceTime } from 'rxjs/operators';
    3. input.valueChanges.pipe(
    4. debounceTime(300)
    5. ).subscribe(value => {
    6. // 执行搜索操作
    7. });
    8. //详细版
    9. import { Component } from '@angular/core';
    10. import { fromEvent } from 'rxjs';
    11. import { debounceTime } from 'rxjs/operators';
    12. @Component({
    13. selector: 'app-debounce-example',
    14. template: '<input (input)="onInput($event)">'
    15. })
    16. export class DebounceExampleComponent {
    17. onInput(event: Event) {
    18. fromEvent(event.target, 'input')
    19. .pipe(
    20. debounceTime(300)
    21. )
    22. .subscribe(() => {
    23. // 执行输入框搜索操作
    24. });
    25. }
    26. }

    节流(Throttle):

    1. //简易版
    2. import { throttleTime } from 'rxjs/operators';
    3. scrollEvent.pipe(
    4. throttleTime(300)
    5. ).subscribe(() => {
    6. // 执行滚动操作
    7. });
    8. //详细版
    9. import { Component } from '@angular/core';
    10. import { fromEvent } from 'rxjs';
    11. import { throttleTime } from 'rxjs/operators';
    12. @Component({
    13. selector: 'app-throttle-example',
    14. template: '<div (scroll)="onScroll($event)">'
    15. })
    16. export class ThrottleExampleComponent {
    17. onScroll(event: Event) {
    18. fromEvent(event.target, 'scroll')
    19. .pipe(
    20. throttleTime(300)
    21. )
    22. .subscribe(() => {
    23. // 执行滚动操作
    24. });
    25. }
    26. }
  2. 使用Angular自带的工具实现防抖和节流:

        防抖(Debounce):

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-debounce-example',
  4. template: '<input (input)="onInput($event)">'
  5. })
  6. export class DebounceExampleComponent {
  7. onInput(event: Event) {
  8. this.debounceSearch();
  9. }
  10. debounceSearch = this.debounce(() => {
  11. // 执行输入框搜索操作
  12. }, 300);
  13. debounce(func, delay) {
  14. let timer;
  15. return function() {
  16. clearTimeout(timer);
  17. timer = setTimeout(() => {
  18. func.apply(this, arguments);
  19. }, delay);
  20. };
  21. }
  22. }

        节流(Throttle):

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-throttle-example',
  4. template: '<div (scroll)="onScroll($event)">'
  5. })
  6. export class ThrottleExampleComponent {
  7. onScroll(event: Event) {
  8. this.throttleScroll();
  9. }
  10. throttleScroll = this.throttle(() => {
  11. // 执行滚动操作
  12. }, 300);
  13. throttle(func, delay) {
  14. let canRun = true;
  15. return function() {
  16. if (!canRun) return;
  17. canRun = false;
  18. setTimeout(() => {
  19. func.apply(this, arguments);
  20. canRun = true;
  21. }, delay);
  22. };
  23. }
  24. }
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/222971
推荐阅读
相关标签
  

闽ICP备14008679号