1,什么是防抖?
触发高频事件后,在n秒内函数只执行一次,如果在n秒内再次触发或触发多次,则重新计算。(在一定时间内只执行最后一次)
例如百度搜索框内的提示
2,什么是节流
高频事件触发,但在 n 秒内只会执行一次,所以节流会稀释函数的执行频率。(假如规定1秒内执行一次,那么你在2秒内无论点击多少次都执行两次,这就是稀释了事件,减少了点击次数)
例如你抢东西的时候一定时间内只能点击一次
区别:
防抖动是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行。
了解原理后下面我们用函数来实现它:
在vue中应该进一步封装到util.js公共函数库中并暴露出来,
//防抖
export function simpleDebounce(fn, delay = 100) {
let timer = null
return function() {
let args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
在需要用到的文件内引入。
import { simpleDebounce } from '@/utils/util';
//在methods中引用
methods: {
testMethods: simpleDebounce( function () {
console.log("测试");
},1000),//这是正确的引用防抖方法,防抖函数会return出一个函数相当vue中的函数,在函数内可以使用this获取data数据等
},
//采坑以下是错误的写法,防抖函数写到函数内
testMethods(){
simpleDebounce( function () {
console.log("测试");
},1000)
},
//采坑2,传入箭头函数
testMethods: simpleDebounce( () => {
console.log("测试");
console.log(this.flag);
},1000),
//如果不封装的情况下需要这样写,注意需要在组件内定义一个全局变量timer
testMethods(){
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
// fn.apply(this, args)
console.log('askdkk',this)
}, 2000)
},
}
节流函数:
function throttle(fn, delay = 200) {
let timer = null
return function () {
if(timer) return
timer = setTimeout(() => {
fn.apply(this,arguments)
timer = null
})
}
}
第二种写法
// 时间戳写法(立刻执行的节流函数)
function throttle(fn, millisecond) {
let start = 0; // 先把开始时间定义为 0
return function () {
let end = Date.now(); // 结束时间直接获取当前
if ((end - start) >= millisecond) { // 然后结束时间 减去 开始时间 如果是大于等于时间参数则可以执行(第一次肯定会立刻执行,因为start为0)
start = end; // 这里结束时间 赋值 给开始时间,为一下次执行做准备
fn.apply(this, arguments); // 执行传来的函数,注意要用apply来改变this指向,因为你不知道这个返回的函数会使用在什么地方
}
}
}