一、防抖函数封装
function debounce(fn,delay) {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this,arguments);
},delay);
}
}
window.onscroll = debounce(function () {
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置:' + scrollTop);
},200)
二、节流函数的封装
<input type="text" value="" id="input">
<script>
function throttle(fn, delay) {
let flag = true;
return function () {
if (!flag) { return; }
flag = false;
setTimeout(() => {
fn.apply(this, arguments);
flag = true;
}, delay);
}
}
$('#input').on('keyup', throttle(function () {
console.log($(this).val());
}, 1000));
</script>