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

2024-03-01 0 402

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

您可能感兴趣的文章:

  • angular异步验证器防抖实例详解
  • angular异步验证防抖踩坑实录
  • Angular请求防抖处理第一次请求失效问题
  • Angular.js 实现带手柄自由调整页面大小的功能
  • Angular7实现拖放Drag Drop示例详解

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 JavaScript Angular实现防抖和节流的示例代码 https://www.u-9.cn/biancheng/javascript/182557.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务