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