学学js防抖与节流
防抖
function debounce(fn, t) {
let time = null;
return function () {
if (time !== null) clearTimeout(time);
time = setTimeout(() => {
fn.apply(this, arguments)
}, t);
}
}
document.querySelector('input').oninput = debounce(function (e) {
console.log(e.target.value)
}, 1000)
节流
function throttle(fn, t) {
let Onoff = true;
return function () {
if (!Onoff) return false;
Onoff = false;
setTimeout(() => {
fn.apply(this, arguments);
Onoff = true;
}, t)
}
}
document.querySelector('input').oninput = throttle(function (e) {
console.log(e.target.value)
}, 1000)