函数防抖就是在函数需要频繁触发的情况下,只有足够的空闲时间,才执行一次。好像公交司机会等人都上车后才出站一样。
应用场景:
- 实时搜索
- 拖拽
实现代码
function debounce(handler, delay){
delay = delay || 300;
var timer = null;
return function() {
var _self = this,
_args = arguments;
clearInterval(timer);
timer = setTimeout(function(){
handler.apply(_self, _args);
}, delay);
}
}
测试用例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<input type="text" id="inp">
<script type="text/javascript">
/**
* 防抖
*/
var oInp = document.getElementById('inp');
function ajax(e) {
console.log(e, this.value)
}
function debounce(handler, delay){
delay = delay || 300;
var timer = null;
return function() {
var _self = this,
_args = arguments;
clearInterval(timer);
timer = setTimeout(function(){
handler.apply(_self, _args);
}, delay);
}
}
oInp.oninput = debounce(ajax, 500);
</script>
</body>
</html>