vue3
// 防抖 因为返回的是一个function,没有执行,这里写了立即执行
let timer: any;
function delay(callback: any, ms: number) {
return (function () {
if (timer != null) {
clearTimeout(timer);
}
timer = setTimeout(callback, ms);
})();
}
function fn() {
console.log('那小子真帅');
}
// 回车事件
let searchContent = () => {
delay(fn, 1000);
};
==================================================》
// 执行返回的方法,就不用写立即执行
let timer: any;
function debounce(callback: any, ms: number = 1000) {
return function () {
if (timer != null) {
clearTimeout(timer);
}
timer = setTimeout(callback, ms);
};
}
// function debounce(callback: any, ms: number = 1000) {
// clearTimeout(timer);
// timer = setTimeout(callback, ms);
// }
export default debounce;
// 调用页面
import debounce from "@/utils/debounce";
let fn = () => {
console.log("那小子真帅!");
};
let debounceEvent = debounce(fn, 1000);
let clickBtn = () => {
debounceEvent();
};
// 节流
let timer: any = null;
export const throttle = (fn: Function, delay: number): Function => {
return (...args: unknown[]) => {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this,args);
timer = null;
}, delay);
};
};
==========================================>
// function throttle(fn: Function, delay: number) {
// return () => {
// if (timer) {
// return;
// }
// timer = setTimeout(() => {
// // 一般直接执行也行 fn.apply(this);
// fn();
// timer = null;
// }, delay);
// };
// }
// export default throttle;