jQuery 方法300ms内重复调用
时间: 2023-08-18 14:29:40 浏览: 41
为了避免在短时间内重复调用 jQuery 方法,可以使用 debounce 或者 throttle 函数。debounce 函数会在最后一次调用之后等待一段时间再执行函数,而 throttle 函数会在一段时间内只执行一次函数。以下是 debounce 和 throttle 函数的示例代码:
debounce 函数示例:
```javascript
function debounce(func, delay) {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
}
```
throttle 函数示例:
```javascript
function throttle(func, delay) {
let timer;
return function () {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null;
}, delay);
}
};
}
```
使用方法如下:
```javascript
$(window).on('resize', debounce(function() {
console.log('resize event debounced');
}, 300));
```
```javascript
$(window).on('scroll', throttle(function() {
console.log('scroll event throttled');
}, 300));
```