//防抖 让某个时间期限内,事件处理函数只执行一次
function antiShakes(fn, time) {
let timeout = null;
return args = () => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(fn, time);
}
}
function demo() {
console.log(input.value)
}
let input = document.querySelector("input");
input.addEventListener("input", antiShakes(demo, 1000));
//节流 在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效
$(window).on('scroll', throttle(function () {
// 判断是否滚动到底部的逻辑
var pageHeight = $('body').height(),
scrollTop = $(window).scrollTop(),
winHeight = $(window).height(),
thresold = pageHeight - scrollTop - winHeight;
// 到页面底部
if (thresold > -100 && thresold <= 20) {
$("script:first").before("<p>hello world</p>");
}
}, 500));
function throttle(fn, interval = 300) {
var canRun = true;
return function () {
//休息时间 暂不接客
if (!canRun) return;
// 工作时间,执行函数并且在间隔期内把状态位设为无效
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, interval);
};
};