函数防抖就是在函数频繁触发情况时,只有足够空闲的时间,才执行一次。
场景:
实时搜索(keyup)
拖拽(mousemove)
上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>防抖</title>
</head>
<body>
<input type="text" id="inp">
<script>
var oInp = document.getElementById('inp');
function debounce(handler,delay){
var timer = null;
return function(){
var _self = this;//绑定this
var _arg = arguments;//绑定事件对象
clearTimeout(timer);
timer = setTimeout(function(){
handler.apply(_self,[_arg]);
},delay)
}
}
function ajax(e){
console.log(e,this.value);
}
oInp.oninput = debounce(ajax,1000);
</script>
</body>
</html>