function throttle(fn, interval) {
// 上一次执行的时间
let last = 0
return function () {
let now = Date.now()
if (now - last >= interval) {
fn.apply(this, arguments)
last = Date.now()
}
}
}
function handle() {
console.log(Date.now());
}
const throttleHandle = throttle(handle, 10)
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
定时器:第一次和最后一次都会延时执行
function throttle(fn, interval) {
let timer = null;
return function () {
let context = this;
let arg = arguments;
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, arg);
timer = null;
}, interval);
}
};
}
function handle() {
console.log(Math.random());
}
const throttleHandle = throttle(handle, 1000);
throttleHandle();
throttleHandle();
throttleHandle();
throttleHandle();
时间戳和定时器相结合
function throttle(fn, delay) {
let timer = null
// 开始时间
let startTime = Date.now()
return function () {
// 当前时间
let curTime = Date.now()
// 剩余时间
let remaining = delay - (curTime - startTime)
clearTimeout(timer)
if (remaining <= 0) {
fn.apply(this,arguments)
startTime=Date.now()
}else{
timer=setTimeout(fn, remaining);
}
}
}