节流和防抖(下)
节流
在(限定时间段内)只触发一次函数,
比如 规定时间间隔为1s ,那这个函数在1s内只执行1次
不管用户触发多少次事件,我触发函数后,1s后才能重新触发
<input class="inp" type="text" />
let input = document.querySelector('.inp');
//间隔1s时间,输出用户在input框的输入
function showVal(e) {
// console.log('this==>', this)
console.log('this.value', this.value);
console.log('e==>', e.target);
}
// 节流函数
function throttle(fn, delay) {
// 被内层函数保护的变量
let bool = false;
return function () {
// 拦截层,当函数正在运行时不执行
if (bool) {
return;
}
// 挂牌函数正在运行
bool = true;
setTimeout(() => {
// 执行函数
fn.apply(this, arguments); //this和arguments分别是修正this指向和修正参数列表
// 函数执行完毕,把牌子去掉
bool = false;
}, delay)
}
}
//绑定监听用户输入事件
input.oninput = throttle(showVal, 1000);