js防抖节流的设置代码如何处理
时间: 2023-07-27 16:13:39 浏览: 57
防抖和节流是两种常用的前端性能优化技术,可以用来减少一些高频触发的事件的触发次数,从而提升页面的性能和用户体验。
下面是防抖和节流的代码实现:
**防抖**
```javascript
// 函数防抖
function debounce(fn, delay) {
let timer = null;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
```
**节流**
```javascript
// 函数节流
function throttle(fn, delay) {
let timer = null;
return function () {
const context = this;
const args = arguments;
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, args);
timer = null;
}, delay);
}
};
}
```
使用方式:
```javascript
// 防抖
const debounceFn = debounce(function () {
console.log('防抖执行了');
}, 1000);
// 节流
const throttleFn = throttle(function () {
console.log('节流执行了');
}, 1000);
// 绑定事件
document.addEventListener('scroll', debounceFn); // 防抖
document.addEventListener('scroll', throttleFn); // 节流
```