用ts语法写出防抖和节流
时间: 2023-10-27 09:16:29 浏览: 47
防抖:
```typescript
function debounce(func: Function, delay: number) {
let timer: ReturnType<typeof setTimeout>;
return function(this: any, ...args: any[]) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
```
节流:
```typescript
function throttle(func: Function, delay: number) {
let timer: ReturnType<typeof setTimeout> | null = null;
let lastTime = 0;
return function(this: any, ...args: any[]) {
const context = this;
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
} else {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
lastTime = Date.now();
}, delay - (now - lastTime));
}
};
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)