函数防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
简单的说,当一个动作连续触发,则只执行最后一次。
如果有人进电梯(触发事件),那电梯将在10秒钟后出发(执行事件监听器),这时如果又有人进电梯了(在10秒内再次触发该事件),我们又得等10秒再出发(重新计时)
限制一个函数在一定时间内只能执行一次。
保证如果电梯第一个人进来后,10秒后准时运送一次,这个时间从第一个人上电梯开始计时,不等待,如果没有人,则不运行
/**
* 防抖函数
* @param {*} cb
* @param {*} wait
*/
function debounce(cb, wait) {
let delay = wait || 500;
let timer;
return () => {
const _this = this;
let args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
cb.apply(_this, args);
}, delay);
};
}
/**
*
* @param {*} cb 回调函数
* @param {*} wait 等待时间
*/
function throttle(cb, wait = 300) {
let delay = wait || 500;
let timer;
return () => {
let _this = this;
let args = arguments;
if (!timer) {
timer = setTimeout(() => {
cb.apply(_this, args);
timer = null;
}, delay);
}
};
}
mine.axml
<view class="root_container">
<input placeholder="Input" onInput="inputHandle" />
<button size="default" type="primary" catchTap='clickHandle'>Button</button>
</view>
mine.js
import { debounce, throttle } from "/utils/index.js";
// 节流使用
clickHandle: throttle(() => {
console.log(new Date());
}, 2000),
// 防抖使用
inputHandle: debounce(() => {
console.log("ajax");
}, 1000)