美文网首页
Solve the problem that frequentl

Solve the problem that frequentl

作者: yilinUnique | 来源:发表于2019-05-05 10:44 被阅读0次

    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 frequentl

          本文链接:https://www.haomeiwen.com/subject/tmlcoqtx.html