防抖函数:
(1) 使用场景:
①登录,注册等应用环境防止多次重复提交
②回调函数执行的频率过高也会有卡顿现象。 可以一段时间过后进行触发去除无用操作
(2) 官方解释:
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
(3) 防抖原理:
一定在事件触发 n 秒后才执行,如果在一个事件触发的 n 秒内又触发了这个事件,以新的事件的时间为准,n 秒后才执行,等触发事件 n 秒内不再触发事件才执行。
(3) 代码实现:
//防抖函数
function debounce(func, wait = 500, immediate = true) {
let timeout
return function (...args) {
let context = this
if (timeout) clearTimeout(timeout)
if (immediate) {
let callNow = !timeout
timeout = setTimeout(function () {
timeout = null
}, wait)
if (callNow) func.apply(context, args)
} else {
timeout = setTimeout(function () {
func.apply(context, args)
}, wait)
}
}
}
//使用
自定义函数名: debounce(function () {
//此处写要执行的逻辑
}),
节流函数:
(1) 使用场景:
①图片懒加载
②滚动事件加载数据
(2) 官方解释:
当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
(3) 节流原理:
如果持续触发事件,每隔一段时间只执行一次函数。
(3) 代码实现:
//节流函数
function throttle (fn, interval) {
var _self = fn, // 保存需要被延迟执行的函数引用
timer, // 定时器
firstTime = true; // 是否是第一次调用
return function () {
var args = arguments;
_me = this;
if (firstTime) { // 如果是第一次调用不需要延迟
_self.apply(_me, args); // 执行fn函数并且修正此函数中this所运行的上下文指向
return firstTime = false;
}
if (timer) { // 如果定时器还在,说明前一次延迟执行还没有完成
return false;
}
timer = setTimeout(function () { // 延迟一段时间执行
clearTimeout(timer);
timer = null;
_self.apply(_me, args); // 执行fn函数并且修正此函数中this所运行的上下文指向
}, interval || 500);
}
}
//使用
自定义函数名: throttle(function () {
//此处写要执行的逻辑
}),