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);

```

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

相关推荐
爱上好庆祝8 分钟前
学习js的第七天(wed APIs的开始)
前端·javascript·css·学习·html·css3
KaMeidebaby1 小时前
卡梅德生物技术快报|冻干工艺开发:注射用心肌肽全流程参数优化与工程化方案
前端·其他·百度·新浪微博
ooseabiscuit1 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
哆啦A梦15882 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3
Moment2 小时前
面试官:如果产品经理给你多个需求,怎么让AI去完成❓❓❓
前端·后端·面试
每天吃饭的羊2 小时前
JSONP
前端
gogoing2 小时前
ESLint 配置字段说明
前端·javascript
Lkstar2 小时前
面试官让我手写 Promise.all / Promise.race / Promise.allSettled,我直接水灵灵地写出来了
javascript·面试
gogoing2 小时前
CSS 属性值计算过程(Computed Value)
前端·css
gogoing2 小时前
webpack 的性能优化
前端·javascript