防抖与节流

防抖

任务在被频繁触发的情况下,只有当触发间隔的时间大于指定时间时,事件才会被触发

	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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值