今天面试面试官问了个问题,大概就是实现input输入几秒后请求将返回的数据放入div中,这里难点就是input框什么时候发起请求,事件节流这个词也是才接触,后来自己百度并做了相应的demo验证实现,将过程记录如下:
<!DOCTYPE html>
<html>
<head>
<title>实现input输入5秒后请求,类似百度那样搜素---事件节流</title>
</head>
<body>
<input type="text" id="inputText">
</body>
<script src="http://www.jq22.com/jquery/jquery-2.1.1.js"></script>
<script type="text/javascript">
$('#inputText').on('input', function () {
var val = $(this).val();
getData('http://localhost:8084', 'GET', {'key': val})
})
function getData (url, method, data) {
$.ajax({
type: method,
url: url,
data: data,
success: function(msg){
console.log(msg)
}
})
}
</script>
</html>
这样写在输入的时候会一直请求,加重服务器的负担。使用js函数节流和去抖动的方法可以缓解频繁触发的事件。
1、debounce去抖动
这里method是触发事件回调函数,context是要调用的回调函数作用域,delay是延迟时间
function debounce(method,delay){
var timer = null;
return function(){
var context = this,args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
method.apply(context,args);
},delay);
}
}
如何使用
search:function(ev){
//30代表上键,40代表下键
if(ev.keyCode==38||ev.keyCode==40){
return;
}
if(ev.keyCode==13){
window.open('https://www.baidu.com/s?wd='+this.searchstr);
this.searchstr='';
}
clearTimeout(this.timer);
var $tt = this;
this.timer = setTimeout(function(){
$tt.getSearchList(); // 获取数据的函数
}, 500);
}
2、throttle节流
function throttle(method, delay, time) {
var timeout,startTime = +new Date();
return function() {
var context = this,
args = arguments,
curTime = +new Date();
clearTimeout(timeout);
// 如果达到了规定的触发时间间隔,触发 handler
if (curTime - startTime >= time) {
method.apply(context, args);
startTime = curTime;
} else {
// 没达到触发间隔,重新设定定时器
timeout = setTimeout(method, delay);
}
};