防抖 function dbbounce(fn, await = 1000) {
let timerId = null
let context = this
let args = arguments
function shake() {
if (timerId) {
clearTimeout(timerId)
timerId = null
}
timerId = setTimeout(function() {
fn.apply(context, args)
}, await)
}
return shake
}
// 第一次立即执行
function dbbounce(fn, fnawait = 200) {
let timerId = null
function shake() {
if (timerId) clearTimeout(timerId)
const callNow = !timerId
timerId = setTimeout(() => {
timerId = null
}, fnawait)
if (callNow) fn.apply(this, arguments)
}
return shake
}
节流 // 时间戳写法,第一次立即执行
function throttle(fn, interval) {
let last = 0;
return function() {
let now = Date.now();
if (now - last >= interval) {
last = now
fn.apply(this, arguments)
}
}
}
// 定时器写法,第一次延迟执行
function throttle(fn, interval) {
let timer = null;
return function () {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(function() {
fn.apply(context, args)
timer = null
}, interval)
}
}
}
// 第三种写法,
function throttle(fn, delay) {
let timer = null;
let startTime = Date.now();
return function() {
let curTime = Date.now();
let remainning = delay - (curTime - startTime);
let context = this;
let args = arguments;
clearTimeout(timer);
if (remainning <= 0) {
fn.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(fn, remainning)
}
}
}