1、防抖:
var Inp = document.getElementById("Inp");
function debounce(handler, delay) {
var timer = null;
return function () {
var _this = this, arg = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
handler.apply(_this, arg);
}, delay)
}
}
function ajax(e) {
console.log(e, this.value);
}
Inp.oninput = debounce(ajax, 1000);
2、节流:
<div id="num">0</div>
<button id="btn">count</button>
<script>
var oDiv = document.getElementById("num");
var oBtn = document.getElementById("btn");
function trottle(handler,wait){
var lastTime = 0;
return function(){
var _this = this;
var nowTime = new Date().getTime();
if(nowTime - lastTime > wait){
handler.apply(_this,arguments);
lastTime = nowTime;
}
}
}
function ajax(e){
console.log(e,this);
oDiv.innerText = parseInt(oDiv.innerText) + 1;
}
oBtn.onclick = trottle(ajax,1000);
</script>