函数防抖和函数节流
函数防抖和函数节流:优化高频率执行js代码的一种手段,js中的一些事件如浏览器的resize、scroll,鼠标的mousemove、mouseover,input输入框的keypress等事件在触发时,会不断地调用绑定在事件上的回调函数,极大地浪费资源,降低前端性能。为了优化体验,需要对这类事件进行调用次数的限制
let oInput = document.querySelector("input");
let timer = null;
oInput.oninput = function( ){
clearTimeout(timer);
timer = setTimeout( ( )=>{
console.log(oInput.value);
},1000);
};
函数节流 减少执行次数 按照指定的时间间隔执行
let timer = null;
document.onmousemove = function( ){
if(timer){
return;
}
timer = setTimeout(( )=>{
console.log("ok");
timer = null;
},1000);
};
浙公网安备 33010602011771号