防抖节流

52 阅读1分钟
export function debounce(func, delay) {
    // console.log("防抖");
    let timerId;
    return function (...args) {
        clearTimeout(timerId);
        timerId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

export function throttle(func, delay) {
    // console.log("节流");
    let lastTime = 0;
    return function (...args) {
        const currentTime = Date.now();
        if (currentTime - lastTime >= delay) {
            func.apply(this, args);
            lastTime = currentTime;
        }
    };
}

使用

import { debounce,throttle } from "@/xxxx/xxxx.js";
const debouncedFunction = debounce((value) => {
  console.log("传入参数",value)
}, 300);
//调用
debouncedFunction("lalalal")
//节流同理