7.防抖节流

// 防抖
export function debounce(fn, delay = 200) {// fn是需要防抖的函数,delay是延迟多少毫秒执行fn
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(fn, arguments);
            timer = null;
        }, delay)
    }
}
 
// 节流
export function throttle(fn, delay = 100) {
    let timer = null;
    return function () {
        if (timer) return;
        timer = setTimeout(() => {
            fn.apply(fn, arguments);
            timer = null;
        }, delay)
    }
}

<el-button @click="clickEvent">防抖</el-button>
<el-button @click="clickEvent2">节流</el-button>
import { debounce,throttle } from "@/utils/handleDebounce";
 
const clickEvent = debounce(
  () => {
    console.log("防抖");
  }, 800);
 
const clickEvent2 = throttle(
  () => {
    console.log("节流");
  }, 800);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容