当某个任务会频繁被触发时,会极大得消耗性能,通过防抖和节流对其进行控制以节省性能
防抖:
利用延时器,让频繁被触发的任务延迟调用,每次该任务调用时都清除上一次的延时器。 缺点就是在一定时间内无法再次触发,不能达到实时触发的效果。
节流:
给频繁执行的任务加上开关,既每次该任务调用后,就进入一定的冷却期,在冷却期间内无论如何触发都不会执行,冷却结束后,触发后再次执行,执行后冷却...
防抖和节流以及应用场景
1.防抖
// 所谓防抖,就是指触发事件后在n秒内函数只能执行一次,如果在n秒内又触发了该事件,则会重新计算函数执行时间
/**
* 立即执行和非立即执行结合
* @desc 函数防抖
* @param func 函数
* @param wait 延迟执行毫秒数
* @param immediate true 表立即执行,false 表非立即执行
*/
function debounce(func,wait,immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
}
2. 节流
//所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率
/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
* @param type 1 表时间戳版,2 表定时器版
*/
function throttle(func, wait ,type) {
if(type===1){
let previous = 0;
}else if(type===2){
let timeout;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}