1、防抖
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
代码:
以闭包的形式返回一个函数,内部解决了this指向的问题,event对象传递的问题
/**
* 防抖
* @param {*} fn 执行函数
* @param {*} delay 防抖间隔时间
*/
const debounce = function (fn, delay = 500) {
let timer = null
return function () {
let content = this;
let args = arguments;
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(content, args)
}, delay)
}
}
const thrDeb = {
debounce
};
export default thrDeb;
2、节流
当持续触发事件时,保证一定时间段内只触发一次事件处理函数
代码:
以闭包的形式返回一个函数,内部解决了this指向的问题,event对象传递的问题
/**
* 节流
* @param {*} fn 执行函数
* @param {*} delay 节流间隔时间
*/
const throttle = function (fn, delay = 500) {
let timer = null
return function() {
if (timer) {
return
}
let content = this;
let args = arguments;
timer = setTimeout(() => {
timer = null
}, delay)
fn.apply(content, args)
}
}
const thrDeb = {
throttle
};
export default thrDeb;
使用方法:
在utils文件夹内创建thrDeb文件,将防抖、节流函数用export抛出
<div @click="getThrottle">节流</div>
methods: {
getThrottle: utils.thrDeb.throttle(function () {
console.log("使用了节流函数!");
}, 1500)
}
总结
防抖:原理是维护一个定时器,将很多个相同的操作合并成一个。规定在delay后触发函数,如果在此之前触发函数,则取消之前的计时重新计时,只有最后一次操作能被触发。
节流:原理是判断是否达到一定的事件来触发事件。某个时间段内只能触发一次函数。
区别:防抖只会在最后一次事件后执行触发的函数,节流不管事件多么频繁,都会保证在规定时间段内触发事件函数