1.节流
// 节流
export function _throttle(fn, wait = 200) {
let last, timer,now;
return function() {
now = Date.now();
if (last && now - last < wait) {
clearTimeout(timer);
timer = setTimeout(function() {
last = now;
fn.call(this, ...arguments);
}, wait);
} else {
last = now;
fn.call(this, ...arguments);
}
};
}
2.防抖
// 防抖
export function _debounce(fn, wait = 200) {
let timer;
return function () {
let context = this;
let args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, wait)
}
}
3.使用
import { _debounce, _throttle } from '@/assets/common/utils';
getList: _throttle(function() {
// 要做的事情
}, 1000)
getList: _debounce(function() {
// 要做的事情
}, 1000)
防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
应用:因为防抖的特性,一直执行最后一次的触发,所以可以用于鼠标移动确定最后一次移动的时候的坐标位置。
输入框的模糊搜索
节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
应用:因为节流是监听到第一次触发事件后就执行,所以可以用来防止按钮多次点击执行多次,且按照第一次点击的事件为准