作用:
使用setTimeout,减少事件触发频率。
原理:
使用input标签的oninput实时监听输入框输入内容变化,为了减少接口调用频率,使用防抖,减少接口请求,可提升用户体验,达到项目优化的目的。
防抖:
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖节流-js</title>
</head>
<body>
<input id="ipt" type="text">
<script>
function debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
let iptDom = document.getElementById('ipt');
let logEvent = () =>{
console.log('iptDom--',iptDom.value);
}
iptDom.oninput = debounce(logEvent, 1000)
</script>
</body>
</html>