实现一个节流函数? 如果想要最后一次必须执行的话怎么实现?
时间: 2023-11-26 12:06:31 浏览: 29
一个基本的节流函数的实现如下:
```
function throttle(func, delay) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
}
}
```
如果想要最后一次必须执行,可以增加一个 `immediate` 参数来控制立即执行的行为:
```
function throttle(func, delay, immediate = false) {
let timer = null;
let previous = 0;
return function() {
const context = this;
const args = arguments;
const now = +new Date();
if (immediate && previous === 0) {
func.apply(context, args);
previous = now;
} else if (now - previous > delay) {
func.apply(context, args);
previous = now;
} else if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
previous = +new Date();
timer = null;
}, delay - (now - previous));
}
}
}
```
然后你可以这样调用:
```
const fn = throttle(() => {
console.log('throttle');
}, 1000, true);
document.addEventListener('scroll', fn);
```