防抖、节流
防抖:
将函数在规定时间内多次触发整合为一次,基本原理就是 delay 时间内再次触发则 重新计时,计时满delay则执行函数
function debounce(fn, delay) { let time = null; return function () { if (time) { clearInterval(time); } time = setTimeout(fn, delay); }; } const test = function () { console.log("1111"); }; const run = debounce(test, 3000); console.log(run) run(); run(); run();
三次调用只会触发一次run函数,适合各种触发
节流:
在一个周期内,函数只执行一次,那么实现的关键就是用本次触发时间和上次触发时间的差值来和 delay 比较,若差值大于 delay 则触发函数 ,可以选择还周期前执行,或者周期后执行
function throttle(fn, delay) { let prevTime = 0; // 在周期开始的时候执行函数 return function () { let nowTime = Date.now(); if (nowTime - prevTime > delay) { fn.apply(this); prevTime = nowTime; } }; } const test = function () { console.log("1111"); }; const run = throttle(test, 3000); console.log(run); run(); run(); run();
function throttle(fn, delay) { let prevTime = Date.now(); // 在周期结束的时候执行函数 return function () { let nowTime = Date.now(); if (nowTime - prevTime > delay) { fn.apply(this); prevTime = nowTime; } }; } const test = function () { console.log("1111"); }; const run = throttle(test, 3000); console.log(run); run(); run(); run(); setTimeout(run,3000)