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

```

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

相关推荐
摘星编程5 小时前
OpenHarmony + RN:Placeholder文本占位
javascript·react native·react.js
a1117765 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得06 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
行走的陀螺仪8 小时前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
摘星编程8 小时前
React Native + OpenHarmony:Spinner旋转加载器
javascript·react native·react.js
We་ct8 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
2301_812731419 小时前
CSS3笔记
前端·笔记·css3
ziblog9 小时前
CSS3白云飘动动画特效
前端·css·css3
越努力越幸运5089 小时前
CSS3学习之网格布局grid
前端·学习·css3
半斤鸡胗9 小时前
css3基础
前端·css