ES6防抖及节流的方法

ES6提供了防抖函数和节流函数来控制函数的执行频率。

  1. 防抖函数(Debounce):在一定时间内,只执行最后一次触发的函数。

```javascript

function debounce(func, delay) {

let timer;

return function (...args) {

clearTimeout(timer);

timer = setTimeout(() => {

func.apply(this, args);

}, delay);

};

}

```

使用示例:

```javascript

function handleInput() {

console.log('Input changed');

}

const debouncedHandleInput = debounce(handleInput, 500);

document.getElementById('input').addEventListener('input', debouncedHandleInput);

```

  1. 节流函数(Throttle):在一定时间内,固定间隔执行函数。

```javascript

function throttle(func, limit) {

let inThrottle;

return function (...args) {

if (!inThrottle) {

func.apply(this, args);

inThrottle = true;

setTimeout(() => {

inThrottle = false;

}, limit);

}

};

}

```

使用示例:

```javascript

function handleScroll() {

console.log('Scrolling');

}

const throttledHandleScroll = throttle(handleScroll, 500);

window.addEventListener('scroll', throttledHandleScroll);

```

这两个函数可以帮助我们优化一些需要控制函数执行频率的场景,比如输入框输入验证、滚动事件处理等。

相关推荐
PineappleCoder1 小时前
性能数据别再瞎轮询了!PerformanceObserver 异步捕获 LCP/CLS,不卡主线程
前端·性能优化
PineappleCoder1 小时前
告别字体闪烁 / 首屏卡顿!preload 让关键资源 “高优先级” 提前到
前端·性能优化
m0_471199632 小时前
【vue】通俗详解package-lock文件的作用
前端·javascript·vue.js
GIS之路2 小时前
GDAL 读取KML数据
前端
今天不要写bug2 小时前
vue项目基于vue-cropper实现图片裁剪与图片压缩
前端·javascript·vue.js·typescript
用户47949283569153 小时前
记住这张时间线图,你再也不会乱用 useEffect / useLayoutEffect
前端·react.js
咬人喵喵3 小时前
14 类圣诞核心 SVG 交互方案拆解(附案例 + 资源)
开发语言·前端·javascript
问君能有几多愁~3 小时前
C++ 日志实现
java·前端·c++
咬人喵喵3 小时前
CSS 盒子模型:万物皆是盒子
前端·css