Solve the problem that frequently click request caused

In project, there are lots of query buttons for users to click. However, if they click too quickly or too frequently, it will cause many problems such as continuous requests bring pressure to the back-end server or leave unfriendly experience in front-end interface. So we can use the below function to ease this situation:

参数说明:fn(调用的防止抖动的函数) duration:(毫秒数) param(fn传入的参数)

function debounce(fn, duration,param){
    // 设置一个定时器 timer
    var timer = null;
    // 闭包函数可以访问 timer
    return function (){
    // 如果事件被触发,清除 timer 并重新开始计时
        clearTimeout(timer)
        timer = setTimeout(function(){
            if(param){
                fn(param); 
            } else{
                fn();
            }
        },duration)
    }
}
function search(){
    console.log("searching…");
}

调用:

$("#searchBtn").on("click", debounce(search,500));

第一页

$("#searchBtn").on("click", debounce(search,500,1));

或者:

$("#searchBtn").click(debounce(function(){
    search();//第一页search(1);
}, 500))

你可能感兴趣的:(Solve the problem that frequently click request caused)