防抖和节流

  |  

防抖和节流是前端对于频繁操作的交互性能优化的重要手段。

注意:: 防抖中采用clearTime()清除定时器, 节流中采用timeout = null重定向本次定时器

防抖

原理: 在事件触发 n 秒后执行回调,如果 n 秒内又被触发,则重新计时。

场景:

  • 按钮提交,防止多次提交,只执行最后一次提交
  • 搜索框联想场景,防止连续发送请求,只执行最后一次提交
// 非立刻执行版
function debounce(func, wait) {
let timeout
return function () {
let context = this
let args = arguments
// 在wait 时间内,如果再次触发,那么清除之前的定时器,开启新的定时器
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}

// 立即执行版(同时结合了非立即执行版)
function debounce(func, wait, immediate) {
let timeout
return function () {
let context = this
let args = arguments
// 在wait时间内再次执行,取消之前的定时器
if (timeout) clearTimeout(timeout)

if (immediate) {
// 如果immediate为true ,第一次进来立刻执行函数
// 开启定时器并不会立刻执行函数,因此取timeout相反的值
let callNow = !timeout
timeout = setTimeout(() => {
// 在定时器里面把timeout置为null
// 即是在0-wait这段时间 !timeout 都是false,因此第一次进来会立刻执行,在wait时间内再次触发不会执行
timeout = null
}, wait)
if (callNow) func.apply(context, args)
} else {
// 如果非立刻执行,那么采用定时器版本
timeout = setTimeout(function () {
func.apply(context, args)
}, wait)
}
}
}

节流

原理:规定 n 秒内只触发一次,如果 n 秒内多次触发,也只有一次生效

场景:

  • 拖拽,防止超高频次触发位置变动
  • 移动事件,(touchmove,mousemove)
  • 缩放(window.resize)
//时间戳版本
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
// let now = +new Date() +new Date得到一个毫秒数
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
// 重新计时
previous = now;
}
}
}

//定时器版本
function throttle(func, wait) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
//定时器+时间戳 实现一次触发两次执行,分别为开头执行,结尾执行
function throttle(func, wait) {
let timeout,context,args,prev=0;
return function()
context = this;
args = arguments;
let now = +new Date()
if(now - prev > wait){
func.apply(context,args);
prev = now;
}else{
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait) }
}
}
}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
,