throttle.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * 函数节流模块封装
  3. *
  4. * @author lautin
  5. * @created 2019-11-20 18:46:01
  6. */
  7. /**
  8. * 节流方法,在指定时间内只执行一次,使用时间戳控制时间
  9. * @param {function} func 事件回调函数
  10. * @param {number} wait 限定输出的时间,建议100-300ms
  11. */
  12. function throttleA(func, wait) {
  13. // 上次执行时间
  14. let previous = 0;
  15. return function () {
  16. // 本次执行时间
  17. let now = Date.now(),
  18. context = this,
  19. args = arguments;
  20. // 定时器以外执行
  21. if (now - previous > wait) {
  22. func.apply(context, args);
  23. // 更新上次时间
  24. previous = now;
  25. }
  26. }
  27. }
  28. /**
  29. * 节流方法,在指定时间内只执行一次,使用定时器控制时间
  30. * @param {function} func 事件回调函数
  31. * @param {number} wait 限定输出的时间,建议100-300ms
  32. */
  33. function throttleB(func, wait) {
  34. // 记录上个定时器
  35. let timer;
  36. return function () {
  37. const context = this,
  38. args = arguments;
  39. // 如果没有定时器则执行
  40. if (!timer) {
  41. func.apply(context, args);
  42. // 更新定时器
  43. timer = setTimeout(() => {
  44. timer = null;
  45. }, wait);
  46. }
  47. }
  48. }
  49. /**
  50. * 兼容执行
  51. * @param {function} func 事件处理函数
  52. * @param {number} wait 节流时间
  53. * @param {mixed} flag 标识符 选择类型
  54. */
  55. export default function throttle(func, wait, flag = null) {
  56. return flag ? throttleB(func, wait) : throttleA(func, wait);
  57. }