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

```

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

相关推荐
Lhuu(重开版13 小时前
JS:正则表达式和作用域
开发语言·javascript·正则表达式
荔枝一杯酸牛奶14 小时前
HTML 表单与表格布局实战:两个经典作业案例详解
前端·html
Charlie_lll15 小时前
学习Three.js–纹理贴图(Texture)
前端·three.js
yuguo.im15 小时前
我开源了一个 GrapesJS 插件
前端·javascript·开源·grapesjs
安且惜15 小时前
带弹窗的页面--以表格形式展示
前端·javascript·vue.js
摘星编程16 小时前
用React Native开发OpenHarmony应用:NFC读取标签数据
javascript·react native·react.js
GISer_Jing16 小时前
AI驱动营销:业务技术栈实战(From AIGC,待总结)
前端·人工智能·aigc·reactjs
GIS之路18 小时前
GDAL 实现影像裁剪
前端·python·arcgis·信息可视化
AGMTI18 小时前
webSock动态注册消息回调函数功能实现
开发语言·前端·javascript
不会Android的潘潘18 小时前
受限系统环境下的 WebView 能力演进:车载平台 Web 渲染异常的根因分析与优化实践
android·java·前端·aosp