防抖
防抖就是在持續(xù)調(diào)用中不會(huì)執(zhí)行,只有當(dāng)停止后一定時(shí)間才會(huì)執(zhí)行一次绍弟。主要作用場(chǎng)景:
1.search搜索聯(lián)想砂豌,用戶在不斷輸入值時(shí),用防抖來(lái)節(jié)約請(qǐng)求資源
2.window觸發(fā)resize的時(shí)候煌寇,不斷的調(diào)整瀏覽器窗口大小會(huì)不斷的觸發(fā)這個(gè)事件,用防抖來(lái)讓其只觸發(fā)一次
//方法一:定時(shí)器
function debounce(fn,wait){
let timer = null;
function retimer(){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(fn,wait)
}
return retimer;
}
//方法二:時(shí)間戳和定時(shí)器
function debounce(fn,wait){
let timer,timeStamp=0;
let context,args;
let run = ()=>{
timer = setTimeout(()=>{
fn.apply(context,args)
},wait)
}
let clean = ()=>{
clearTimeout(timer)
}
return function(){
content = this;
args = arguments;
let now = (new Date()).getTime();
if(now-timeStamp < wait){
clean();
run();
}else{
run();
}
timeStamp = now;
}
}
//方法三
function debounce(fn,wait){
let timer,timeStamp=0;
let context,args;
let run = (timerInterval)=>{
timer = setTimeout(()=>{
let now = (new Date()).getTime();
let interval = now - timeStamp;
if(interval<timerInterval){
timeStamp = now;
run(wait-interval);
}else{
fn.apply(context,args);
clearTimeout(timer);
timer = null;
}
},timerInterval)
}
return function(){
content = this;
args = arguments;
let now = (new Date()).getTime();
timeStamp = now;
if(!timer){
run(wait);
}
}
}
方法的調(diào)用
<input id="input" >
function handler(){
console.log('111111');
}
document.getElementById('input').addEventListener('keydown',debounce(handler,1000))
window.addEventListener('resize',debounce(handler,1000))
節(jié)流
防抖就是在一段時(shí)間內(nèi)持續(xù)調(diào)用逾雄,但只會(huì)執(zhí)行一次阀溶。
主要作用場(chǎng)景:
1.鼠標(biāo)不斷點(diǎn)擊觸發(fā),mousedown(單位時(shí)間內(nèi)只觸發(fā)一次)
2.監(jiān)聽滾動(dòng)事件嘲驾,比如是否滑到底部自動(dòng)加載更多
//方法一
function throttle(fn,wait){
let canRun = true;
return function(){
if(!canRun){
return;
}else{
canRun = false;
setTimeout(()=>{
fn.apply(this,arguments);
canRun = true;
},wait);
}
}
}
//方法二
function throttle(fn,wait){
let timer;
let context,args;
let run = ()=>{
timer = setTimeout(()=>{
fn.apply(content,args);
clearTimeout(timer);
timer = null;
},wait)
}
return function(){
context = this;
args = arguments;
if(!timer){
run();
}
}
}
//方法三
function(func, delay) {
var timer = null; // 使用閉包淌哟,緩存變量
var prev = Date.now(); // 最開始進(jìn)入滾動(dòng)的時(shí)間
return function() {
var context = this; // this指向window
var args = arguments;
var now = Date.now();
var remain = delay - (now - prev); // 剩余時(shí)間
clearTimeout(timer);
// 如果剩余時(shí)間小于0,就立刻執(zhí)行
if (remain <= 0) {
func.apply(context, args);
prev = Date.now();
} else {
timer = setTimeout(func, remain);
}
}
}
方法的調(diào)用
<div id="container"></div>
function handler() {
console.log('111111');
}
document.getElementById('container').addEventListener('click', throttle(handler, 1000));