防抖
防抖就是在持续调用中不会执行,只有当停止后一定时间才会执行一次。主要作用场景:
1.search搜索联想,用户在不断输入值时,用防抖来节约请求资源
2.window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
//方法一:定时器
function debounce(fn,wait){
let timer = null;
function retimer(){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(fn,wait)
}
return retimer;
}
//方法二:时间戳和定时器
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);
}
}
}
方法的调用
<input id="input" >
function handler(){
console.log('111111');
}
document.getElementById('input').addEventListener('keydown',debounce(handler,1000))
window.addEventListener('resize',debounce(handler,1000))
节流
防抖就是在一段时间内持续调用,但只会执行一次。
主要作用场景:
1.鼠标不断点击触发,mousedown(单位时间内只触发一次)
2.监听滚动事件,比如是否滑到底部自动加载更多
//方法一
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(); // 最开始进入滚动的时间
return function() {
var context = this; // this指向window
var args = arguments;
var now = Date.now();
var remain = delay - (now - prev); // 剩余时间
clearTimeout(timer);
// 如果剩余时间小于0,就立刻执行
if (remain <= 0) {
func.apply(context, args);
prev = Date.now();
} else {
timer = setTimeout(func, remain);
}
}
}
方法的调用
<div id="container"></div>
function handler() {
console.log('111111');
}
document.getElementById('container').addEventListener('click', throttle(handler, 1000));