防抖节流如何用代码实现
时间: 2024-05-29 16:06:58 浏览: 15
防抖和节流是前端开发中常用的性能优化技术,主要应用在一些频繁触发的事件中,比如滚动、输入等。它们的主要区别在于防抖是在事件触发后一定时间内没有再次触发才执行函数,而节流是每隔一定时间就会执行一次函数。下面是防抖和节流的代码实现:
防抖:
```
function debounce(func, delay) {
let timerId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timerId);
timerId = setTimeout(function() {
func.apply(context, args);
}, delay);
}
}
```
这里的 `func` 是要执行的函数,`delay` 是延迟的时间。
节流:
```
function throttle(func, delay) {
let lastTime = 0;
return function() {
const context = this;
const args = arguments;
const now = new Date().getTime();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
}
}
}
```
这里的 `func` 是要执行的函数,`delay` 是时间间隔。