2-20、防抖和节流有什么区别?手写防抖和节流

31 阅读1分钟

知识点

节流

<script>
    const oDiv = document.querySelector("div")

    oDiv.addEventListener(
        "drag",
        throttle(function (e) {
            console.log(e.clientX);
        }))

    function throttle(fn) {
        let timer = null;
        return function () {
            if (timer) return;
            timer = setTimeout(() => {
                fn.apply(this, arguments)
                timer = null;
            }, 100)
        }

        // let timer = null;
        // return function () {
        //     if (timer) return;
        //     timer = setTimeout(() => {
        //         fn.apply(this.arguments);
        //         timer = null
        //     }, 100);
        // };
    }
</script>

image.png

防抖

<script>

    const oInp = document.querySelector("input");

    oInp.addEventListener(
        "keyup",
        debounce(function () {
            console.log(oInp.value + "取后台请求");
        }));

    function debounce(fn) {
        let timer = null;
        return function () {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                fn.call(this, arguments)
            }, 1000)
        }
    }
</script>

image.png