Anti-shake and throttling are commonly used methods to optimize front-end performance .
1. Anti-shake
1. Anti-shake means that the callback function is executed after n seconds after the event is triggered. If it is triggered again within these n seconds, the timing will be restarted. The implementation of anti-shake can use setTimeout function and closure.
2. Anti-shake package
export function debounce(fn: Function, delay = 200) {// 参数1:调用的函数或者是请求 参数2:延迟多少毫秒才执行
let timer: NodeJS.Timeout | null = null;//设定一个,在没有执行定时器为null
return function () {
if (timer) {//
clearTimeout(timer)
}
timer = setTimeout(() => {//创建一个定时器在指定时间内触发次此函数
fn.apply(this, arguments)//fn需要防抖的函数,arguments调用函数参数的信息
timer = null
}, delay)
console.log(timer, 'timer')
}
}
3. Use it on the login page, introduce the packaged anti-shake, call the packaged anti-shake
import { debounce } from "@/utils/DebounceThrottle";//Import packaged debounce
const submitForm = debounce(login, 200)//Call packaged debounce parameter 1: request interface data, parameter 2: delay 200 milliseconds
4. Application scenarios
- Search box Search input. Only the user needs to enter the last time before sending the request
- Mobile phone number, email verification input detection
- window size
resize
. Just calculate the window size after the window resizing is done. Prevent re-rendering.
Two. Throttling
1. Throttling means that the callback function is executed only once within a period of time. Throttling can be achieved using the setTimeout function and closures.
2. Throttling package
export function throttle(fn: Function, delay = 100) {
let timer: NodeJS.Timeout | null = null;//首先设定一个变量,在没有执行我们的定时器为null
return function () {
if (timer) return; //当我们发现这个定时器存在时,则表示定时器已经在运行中,需要返回
timer = setTimeout(() => {
fn.apply(fn, arguments);//apply更改this指向,指向正在操作的组件实例传入参数
timer = null;
}, delay)
}
}
3. Application scenarios
- Scroll to load, load more or scroll to the bottom to listen
- Search box, search association function