• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
smileyqp
https://github.com/smileyqp
博客园    首页    新随笔    联系   管理    订阅  订阅

(十四)防抖和节流

防抖

  • 适用于表单输入验证
  • 防止表单多次提交
//延迟执行的防抖函数
//当上一次没有完成时候再次触发就清除重新计时;但是这种是只有在最后才会触发func
function debounce(func,wait = 500){
	let timer = null;
	return function(...args){
		if timer clearTimeout(timer);
		timer = setTimeout(function(){
			func.apply(this,args)
		},wait)
	}
}
//是否立即执行的一个防抖函数
function debounce(func,wait = 500,immediate = true){
	let timer,context,args;
		const later = () => setTimeout({
			timer = null;
		if(!immediate){
			func.apply(context,args)
			context = args = null;
		}
	},wait)

	
	return function(...params){
		if(!timer){					//如果timer为空
			timer = later()
			if(immediate){			//如果立即执行的话
				func.apply(this,params)
			}else{
				context = this;
				args = params;
			}
		}else{
			timer = clearTmeout();
			timer = later();
		}
	}
}

总结防抖函数是否立即执行的情况

防抖和节流实际应用

function debounce(fn,delay = 500){
	var t = null;
	return function(){
		if (t != nul){clearTimeout(t)};
		setTimeout(fn,delay);
	}
}
	//时间间隔超过500才执行
function throttle(fn,delay = 500){
	var lasttime = new Date().getTime();//throttle方法执行时候发生
	return function(){
		var now = new Date().getTime();//onscroll被触发的时候发生
		if(now - lasttime > 500){
			fn();
			lasttime = now;//每次执行后将时间设置称当前;
		}	
	}

}	

window.onscroll = debounce(function(){
	console.log('调用了1次');
},500)
防抖:固定时间内反复触发,只执行一次
节流:频次触发;固定时间间隔只执行一次
posted @ 2019-09-16 17:26  smileyqp  阅读(130)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3