JS节流
函数节流就是预定一个函数只有在大于等于执行周期时才会执行,周期内不调用不执行,好像水滴攒到一定重量才会落下一样。
场景
- 窗口调整(resize)
- 页面滚动(scroll)
- 疯狂点击(mousedown)
疯狂点击
<div id = 'd'>0</div>
<button id = 'bnt'>click</button>
<script>
var oDiv = document.getElementById('d');
var oBtn = document.getElementById('bnt');
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>
JS防抖
函数防抖就是函数在需要频繁触发情况时,只有足够空闲的时间,才执行一次。好像公交司机会等人都上车后才出站一样。
场景
- 实时搜索(keyup)
- 拖拽(mousemove)
例子
<input type = "text" id = "inp"/>
<script>
var oInp = document.getElementById('inp');
var timer = null;
function debounce(handler, delay){
var timer = null;
return function (){
var _self = this, _arg = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
ajax.apply(_self,_arg);
},1000)
}
}
function ajax(e){
console.log(e, this.value);
}
oInp.oninput = debouce(ajax, 2000);
</script>