当前位置: 代码网 > it编程>前端脚本>AngularJs > Angular实现防抖和节流的示例代码

Angular实现防抖和节流的示例代码

2024年05月15日 AngularJs 我要评论
在angular中实现防抖和节流的方法有多种,这篇博客主要是详细介绍两种常用的方法:使用rxjs操作符和使用angular自带的工具。使用rxjs操作符实现防抖和节流:防抖(debounce)://简

在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防抖和节流的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com