防抖
任务在被频繁触发的情况下,只有当触发间隔的时间大于指定时间时,事件才会被触发
function ajax(){
console.log('111');
}
function debounce(func,time){
let timer=null;
return function(){
clearTimeout(timer);
timer=setTimeout(()=>{
// this是window
console.log(this);
func.call(this,arguments);
},1000)
}
}
Example 1:
滚动图片懒加载
首先看一下offsetTop,innerHeight,scrollTop这几个值都代表什么?
offsetTop返回是相对带有定位父级元素的上方偏移量
innerHeight 是整个窗口的大小值;
scrollTop这个属性值代表滚动距离;
所以当offsetTop < innerHeight+scrollTop 时图片加载
//
<img data-src="img/face.jpg" />
var img=document.querySelector('img');
function handle(){
console.log(img.offsetTop);
console.log(window.innerHeight)
console.log(document.documentElement.scrollTop);
scrollTop=document.body.scrollTop+document.documentElement.scrollTop
if(img.offsetTop<window.innerHeight+scrollTop){
console.log(img.dataset.src)
img.src = img.dataset.src;
}
}
function debouce(func,time){
let timer=0;
return function(){
clearTimeout(timer);
timer=setTimeout(()=>{
console.log(this);
func.call(this,arguments)
},time)
}
}
document.body.onscroll=debouce(handle,1000);
节流
与防抖类似:指定时间间隔执行一次,也可以不用定时器,用时间戳来实现
function ajax(){
console.log('111');
}
function throttle(func,time){
let tag=true;
return function(){
if(!tag){return;}
tag=false;
setTimeout(()=>{
// this是window
console.log(this);
func.call(this,arguments);
tag=true;
},1000)
}
}
时间戳
var throttle = function(func, delay){
var prev = Date.now();
return function(){
var context = this;
var now = Date.now();
if(now-prev>=delay){
func.apply(context,arguments);
prev = Date.now();
}
}
}