function throttle(fn, time) {
let timer;
return function(){
const args = arguments;
const _that = this;
if(timer) {
return;
}
timer = setTimeOut(() => {
fn.call(_that, args);
timer = null;
}, time);
}
}
// 简单的节流函数 wait的延时保证程序的健壮性
function throttle (func, mustRun, wait) {
let timeout,
startTime = new Date().getTime();
return function () {
let that = this,
args = arguments,
curTime = new Date().getTime();
clearTimeout(timeout);
// 如果达到了时间间隔,触发 handler
// 如果没有,设置一个延时,假设为最后一次
if (curTime - startTime >= mustRun) {
func.apply(that, args);
startTime = curTime;
} else {
// 没达到触发间隔,重新设定定时器 ,
// 保证不丢失最后一次触发,如果中间再触发,会在之前被clear掉
timeout = setTimeout(func, wait);
}
};
}
let timer1 = setInterval(throttle(fn, 500), 10); // 每500ms执行一次
function debounce(fn, wait) {
var timer = null;
return function () {
var context = this
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args)
}, wait);
}
}
console.time('debounce')
let fn = function () {
console.timeEnd('debounce', ‘’)
}
let timer1 = setInterval(debounce(fn, 500, true), 10);
let timer2 = setTimeout(() => { clearInterval(timer1) }, 1000);
// 函数被执行
// debounce: 1512.098ms