意义: 提升程序执行效率, 减少计算资源的浪费, 优化用户体验。
节流 throttle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
function throttle(fn, interval) { let timer = null; console.log('arguments',arguments) return function(){ if (timer) return;
fn.apply(this, arguments);
timer = setTimeout(() => { timer = null; }, interval); }; }
const boxDOM = document.querySelector(".box"); boxDOM.addEventListener( "drag",
throttle((e) => { console.log(e.offsetX, e.offsetY, " -- ", new Date().toISOString()); }, 1000) );
|
防抖 debounce
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
const inputDOM = document.getElementById("hInput");
function debounce(fn, interval) { let timer = null; return function () { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(this, arguments); }, interval); }; }
inputDOM.addEventListener( "input", debounce(() => { console.log("发送搜索请求"); }, 600) );
|