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

```

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

相关推荐
码农捻旧1 分钟前
解决Mongoose “Cannot overwrite model once compiled“ 错误的完整指南
javascript·数据库·mongodb·node.js·express
淡笑沐白10 分钟前
探索Turn.js:打造惊艳的3D翻页效果
javascript·html5·turn.js
sunxunyong1 小时前
yarn任务筛选spark任务,判断内存/CPU使用超过限制任务
javascript·ajax·spark
Ynov1 小时前
详细解释api
javascript·visual studio code
左钦杨1 小时前
IOS CSS3 right transformX 动画卡顿 回弹
前端·ios·css3
NaclarbCSDN1 小时前
Java集合框架
java·开发语言·前端
三天不学习2 小时前
一文讲透 Vue3 + Three.js 材质属性之皮革篇【扫盲篇】
javascript·webgl·three.js·材质
进取星辰2 小时前
28、动画魔法圣典:Framer Motion 时空奥义全解——React 19 交互动效
前端·react.js·交互
不爱吃饭爱吃菜3 小时前
uniapp微信小程序-长按按钮百度语音识别回显文字
前端·javascript·vue.js·百度·微信小程序·uni-app·语音识别
程序员拂雨3 小时前
Angular 知识框架
前端·javascript·angular.js