前端开发中频繁的触发事件执行,对于DOM操作,资源加载等耗费性能的处理,很可能导致页面卡顿,甚至浏览器崩溃。函数节流和防抖应运而生。
防抖
<body>
<input type="text" id="inp"></input>
</body>
<script>
var oInp = document.getElementById('inp')
var timer = null,
function debounce(handler,delay) {
return function(){
var _self = this,
_args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
handler.apply(_self,_args);
},delay)
}
}
function ajax(e){
console.log(e,this.value)
}
oInp.oninput = debounce(ajax,1000);
节流
就是预定一个函数只有在大于等于执行周期的时候才执行,周期内调用不执行。
窗口调整,页面滚动,疯狂点击。
<body>
<div class="show">0</div>
<button class="btn">click</button>
</body>
<script>
var oDiv = document.getElementsByClassName('show')
var oBtn = document.getElementsByClassName('btn')
function throttle(handler,wait){
var lastTime = 0;
return function(e){
var nowTime = new Date().getTime();
if(nowTime-lastTime > wait){
handler.apply(this,arguments);
lastTime = nowTime;
}
}
}
function buy(e){
console.log(this,e)
oDiv.innerText = parseInt(oDiv.innerText) + 1;
}
oBtn.onclick = throttle(buy,1000);
</script>