1.节流:
概念:
节流是一种优化技术,它可以限制一段时间内函数被调用的次数。这对于一些高频事件(如滚动、鼠标移动等)的性能优化非常有用,因为它可以减少函数的执行次数,从而减少浏览器的负担。
实现方案:
1. ts实现方案:
/**
* 节流实现方案
* @param func 需要节流的函数
* @param delay 节流时间间隔
* @returns 节流后的函数
*/
export function throttle(func: Function, delay: number): Function {
let timer: number | null = null;
return function (...args: any[]) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
2. css实现方案:
/* 节流css实现方案 */
* {
transition: all 0.3s ease-out;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
animation-duration: 0.001s;
animation-name: throttle;
}
@keyframes throttle {
from {
opacity: 1;
}
to {
opacity: 1;
}
}
2.防抖:
概念:
防抖是一种优化技术,它可以在一定时间内延迟函数的执行,直到事件停止触发。这对于一些高频事件(如输入框输入、窗口大小改变等)的性能优化非常有用,因为它可以减少函数的执行次数,从而减少浏览器的负担。
实现方案:
1. ts实现方案
/**
* 防抖实现方案
* @param func 需要防抖的函数
* @param delay 防抖时间间隔
*/
export function debounce(func: Function, delay: number) {
let timer: ReturnType<typeof setTimeout> | null = null;
return function (...args: any[]) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
2. css实现方案:
/* 防抖css实现方案 */
* {
transition: all 0.3s ease-out;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
}