console
function debounce(fn, ms) {
let timerId;
return function () {
timerId && clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, arguments);
}, ms);
}
}
function throttle(fn, ms) {
let timerId;
return function () {
if (!timerId) {
timerId = setTimeout(() => {
timerId = null;
fn.apply(this, arguments);
}, ms);
}
}
}
$(function () {
$("#no-debounce").keyup((e) => {
console.log(e.target.value);
});
$("#debounce").keyup(debounce((e) => {
console.log(e.target.value);
}, 500));
})
$(function () {
$("#no-throttle").mousemove((e) => {
console.log("clientX:" + e.clientX + ", clientY:" + e.clientY);
});
$("#throttle").mousemove(throttle((e) => {
console.log("clientX:" + e.clientX + ", clientY:" + e.clientY);
}, 500));
})
不防抖:<input id="no-debounce" />
防抖:<input id="debounce" />
<hr>
节流:<div id="no-throttle" style="width:300px; height:100px; background:#ff0000"></div>
节流:<div id="throttle" style="width:300px; height:100px; background:#ff00ff"></div>