1 /** 2 * 防抖函数 3 * @param {*} func 防抖后要执行的回调 4 * @param {*} wait 等待时间 5 * @param {*} immediate 6 */ 7 function debounce(func, wait, immediate) { 8 let timeout, args, context, timestamp, result; 9 10 const later = function () { 11 // 距上一次触发时间间隔 12 const last = +new Date() - timestamp; 13 14 // 上次被包装函数被调用时间间隔last小于设定时间间隔wait 15 if (last < wait && last > 0) { 16 timeout = setTimeout(later, wait - last); 17 } else { 18 timeout = null; 19 // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用 20 if (!immediate) { 21 result = func.apply(context, args); 22 if (!timeout) context = args = null; 23 } 24 } 25 }; 26 27 return function (...args) { 28 context = this; 29 timestamp = +new Date(); 30 const callNow = immediate && !timeout; 31 // 如果延时不存在,重新设定延时 32 if (!timeout) timeout = setTimeout(later, wait); 33 if (callNow) { 34 result = func.apply(context, args); 35 context = args = null; 36 } 37 38 return result; 39 }; 40 }