防抖
定义:对于短时间内连续触发得事件,防抖得意义就是让某个时间期限内,事件处理函数只执行一次
应用场景:
- scroll事件滚动触发
- 搜索框输入查询
- 表单验证
- 按钮提交事件
- 浏览器窗口缩放,reslize事件
function debounce(func,wait){let timeout = null;return function(){let context = arguments;let _this = this;clearTimeout(timeout);timeout = setTimeout(function(){func.apply(_this,context)},wait)}}
节流
定义:如果你持续触发事件,每隔一段事件,只执行一次事件。
function throttle(func,wait){let context,argslet old = 0return function(){context = thisargs = argumentslet now = new Date().valueOf()if (now - old>wait){func.apply(context,args)old = now}}}
