loading.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import {
  2. simpleDebounce,
  3. throttle
  4. } from "./util.js"
  5. // 与 request.js 中 timeout 保持一致,避免循环依赖(request.js 会 import 本文件的 showLoading/hideLoading)
  6. const DEFAULT_LOADING_TIME = 1000 * 60;
  7. let loadingCount = 0; //loading发起时加的计数
  8. let currentState = {};
  9. const defaultState = {
  10. loadingText: "正在加载…",
  11. loadingTime: DEFAULT_LOADING_TIME
  12. }
  13. const endLoading = simpleDebounce(() => {
  14. currentState = {};
  15. uni.hideLoading();
  16. }, 500)
  17. const throttleShowLoading = throttle(500, () => {
  18. uni.showLoading({
  19. title: currentState.loadingText
  20. });
  21. if (currentState.loadingTime) {
  22. setTimeout(() => {
  23. endLoading();
  24. loadingCount = 0
  25. }, currentState.loadingTime)
  26. }
  27. })
  28. export const showLoading = (state = defaultState) => {
  29. if (loadingCount === 0) {
  30. currentState = state;
  31. throttleShowLoading();
  32. }
  33. loadingCount += 1;
  34. };
  35. export const hideLoading = () => {
  36. if (loadingCount <= 0) {
  37. return;
  38. }
  39. loadingCount -= 1;
  40. if (loadingCount === 0) {
  41. endLoading();
  42. }
  43. };