通过JQuery来理解防抖和节流

2,544 阅读1分钟

通过JQuery来理解防抖和节流

一、简介
  • 防抖(debounce):无论执行多少次都以最后一次为准(电脑自动休眠就是经典的防抖)
  • 节流(throttle):调用了多次只要第一次调用有效( 单位时间内多次触发函数,也只有一次生效 )
二、防抖节流代码
<--HTML部分-->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
​
    <button id="debounce">防抖</button>
    <button id="throttle">节流</button>
//JS部分
function move(e) {
    console.log("Hello World!");
}
// 防抖
function debounce(fn) {
    var debItem = null
    return function () {
        var arg = arguments[0]   //获取事件
        if (debItem) {
            clearTimeout(debItem)
        }
        debItem = setTimeout(function () {
            fn(arg)              //事件传入函数
        }, 2000)
    }
}
// 节流
function throttle(fn) {
    var thrItem = null
    return function () {
        var arg = arguments[0]  //获取事件
        if (thrItem) { return }
        thrItem = setTimeout(function () {
            fn(arg)             //事件传入函数
            thrItem = null
        }, 2000)
    }
}
$(document).ready(function () {
    $("#debounce").on('click', debounce(move));
    $("#throttle").on('click', throttle(move));
});

\