js封装防抖和节流函数使用及说明
作者:霸气小男
防抖和节流是前端优化事件处理的两种技术,防抖通过设置等待时间,只有在指定时间内没有再次触发事件时,才会执行目标函数,节流则是固定时间内只执行一次,无论事件触发多少次,生活类比分别为电梯门倒计时和水龙头限流接水
防抖
实现原理:事件触发后,等待指定时间;若在这段时间内再次触发,则重新计时;直到最后一次触发后超过指定时间,才真正执行目标函数
生活类比:
- 每次有人进电梯(触发事件),门会重新倒计时 5 秒才关闭
- 如果 5 秒内又有人进来,重新计时
- 直到 5 秒内没人再进来,门才真正关闭(执行函数)
常规版
/**
* @description 防抖
* @param {*} fn
* @param {*} delay
* @return {*}
*/
export const debounce = (fn, delay) => {
let timer
return function () {
const _this = this
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function () {
fn.apply(_this, args)
}, delay)
}
}简洁版
const debounce = (fn, d = 300) => {
let t;
return (...a) => (clearTimeout(t), t = setTimeout(() => fn(...a), d));
};如何使用
//引入你封装的防抖文件
import { debounce } from './debounce.js';
const handleSearch = debounce((val)=> {
console.log(val);
}, 500);节流
实现原理:固定时间内只执行一次,无论事件触发多频繁,每隔 n 毫秒才执行一次目标函数
生活类比:
- 把水龙头开到最大,但下方杯子每 1 秒只允许接一次水
- 1 秒内再怎么开水,杯子也只接一次
常规版
/**
* @description 节流
* @param {*} fn
* @param {*} delay
* @return {*}
*/
export const throttle = (fn, delay) => {
let timer
return function () {
const _this = this
const args = arguments
if (!timer) {
timer = setTimeout(function () {
timer = null
fn.apply(_this, args)
}, delay)
}
}
}简洁版
const throttle = (fn, d = 300) => {
let t;
return (...a) => {
if (!t) t = setTimeout(() => (t = null, fn(...a)), d);
};
};如何使用
//引入你封装的节流文件
import { throttle } from './throttle.js';
const handleScroll = throttle(function (e) {
console.log(e);
}, 300);总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
