debounce.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * 函数防抖模块封装
  3. * @author lautin
  4. * @created 2019-11-20 18:44:32
  5. */
  6. /**
  7. * 防抖函数,在一个时段内反复触发时 更新定时器为最后一次延迟执行
  8. * 该操作欠缺的地方在于 延迟执行,响应比较慢 最好是先执行
  9. * @param {function} func 事件回调函数
  10. * @param {number} wait 延迟等待时间,建议100-300ms左右
  11. */
  12. function debounceA(func, wait) {
  13. // 初始化定时器为空
  14. let timer = null;
  15. // 返回一个防抖的闭包函数,使用闭包来持久存储定时器
  16. return function () {
  17. const context = this, // this为事件源DOM
  18. args = arguments; // arguments包含event
  19. // 如果已有定时器 则取消上次的任务
  20. if (timer) clearTimeout(timer);
  21. // 更新定时器,本次(最后)任务n毫秒后触发
  22. timer = setTimeout(() => {
  23. // 还原事件回调函数触发时的环境
  24. func.apply(context, args);
  25. }, wait);
  26. }
  27. }
  28. /**
  29. * 防抖函数,在一个时段内反复触发时 更新定时器为最后一次延迟执行
  30. * 该方法 先执行 后延迟 响应灵敏更高
  31. * @param {function} func 事件回调函数
  32. * @param {number} wait 延迟等待时间,建议100-300ms左右
  33. */
  34. function debounceB(func, wait) {
  35. let timer = null;
  36. return function () {
  37. const context = this,
  38. args = arguments;
  39. // 首先取消中间的定时器,重新开始计时
  40. if (timer) clearTimeout(timer);
  41. //先加载本次任务,
  42. if (!timer) func.apply(context, args);
  43. // 再进行定时器控制
  44. timer = setTimeout(() => {
  45. timer = null;
  46. }, wait);
  47. }
  48. }
  49. export default function debounce(func, wait, immediate = false) {
  50. return immediate ? debounceB(func, wait) : debounceA(func, wait);
  51. }