防抖
事件次数触发过于频繁,只取最后一次操作。
<body>
<input id="myInput" type="text">
</body>
<script>
// 防抖
let myInput = document.getElementById('myInput');
myInput.oninput = debounce(handle, 500);
function debounce(fn, delay) {
let timer;
return function(e) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn(e);
}, delay)
}
}
function handle(e) {
console.log(e.target.value);
}
</script>
节流
在规定时间内只执行一次操作。
<body>
<input id="myInput" type="text">
</body>
<script>
// 节流
let myInput = document.getElementById('myInput');
myInput.oninput = control(handle, 500);
function control(fn, delay) {
let timer;
let flag = false;
return function(e) {
if (flag) {
return;
}
flag = true;
timer = setTimeout(() => {
fn(e);
flag = false;
}, delay);
}
}
function handle(e) {
console.log(e.target.value);
}
</script>