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:
參數(shù)說明:fn(調(diào)用的防止抖動的函數(shù)) duration:(毫秒數(shù)) param(fn傳入的參數(shù))
function debounce(fn, duration,param){
// 設(shè)置一個定時器 timer
var timer = null;
// 閉包函數(shù)可以訪問 timer
return function (){
// 如果事件被觸發(fā)把跨,清除 timer 并重新開始計時
clearTimeout(timer)
timer = setTimeout(function(){
if(param){
fn(param);
} else{
fn();
}
},duration)
}
}
function search(){
console.log("searching…");
}
調(diào)用:
$("#searchBtn").on("click", debounce(search,500));
第一頁
$("#searchBtn").on("click", debounce(search,500,1));
或者:
$("#searchBtn").click(debounce(function(){
search();//第一頁search(1);
}, 500))