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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。