防抖(debounce)
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn();
}, delay);
};
}
let input = document.getElementById("input");
input.addEventListener("input", debounce(changeValue, 2000));
function changeValue() {
console.log("change");
}
节流(throttle)
function throttle(fn, delay) {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(() => {
fn();
timer = null;
}, delay);
}
};
}
let box = document.getElementById("box");
box.addEventListener("touchmove", throttle(moveBox, 2000));
function moveBox() {
console.log("move");
}