js防抖方法

 

<button id="debounce">点我防抖!</button>

<script>
    $('#debounce').on('click', debounce());
    
    function debounce() {
        let timer;  // 使用闭包,多次调用都能访问到同一个变量,而不是生成新的变量
        return function () {
            clearTimeout(timer);
            timer = setTimeout(() => {
                // 需要防抖的操作...
                console.log("防抖成功!");
            }, 500);
        }
    }
</script>

防抖函数的封装使用

// 防抖函数
function debounce(fn,delay) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this,arguments);
        },delay);
    }
}


window.onscroll = debounce(function () {
    let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    console.log('滚动条位置:' + scrollTop);
},200)

// jq
$(window).on('scroll', debounce(function () {
    console.log("防抖成功!");
}, 200))

 


<button id="throttle">点我节流!</button>

<script>
    $('#throttle').on('click', throttle());
    
    function throttle(fn) {
        let flag = true;
        // 使用闭包,方法多次调用都能访问到同一个变量,而不是生成新的flag变量
        return function () {
            if (!flag) { return; }
            flag = false;
            setTimeout(() => {
                console.log("节流成功!");
                flag = true;
            }, 1000);
        };
    }
</script>

节流函数的封装使用

<input type="text" value="" id="input">

<script>
    // 节流函数
    function throttle(fn, delay) {
        let flag = true;
        return function () {
            if (!flag) { return; }
            flag = false;
            setTimeout(() => {
                fn.apply(this, arguments);
                flag = true;
            }, delay);
        }
    }


    $('#input').on('keyup', throttle(function () {
        console.log($(this).val());
        // ajax后台请求....
    }, 1000));
</script>

 

posted @ 2023-12-21 16:52  Shimily  阅读(147)  评论(0)    收藏  举报