夜猫子的知识栈 夜猫子的知识栈
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

夜猫子

前端练习生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • JavaScript文章

    • 33个非常实用的JavaScript一行代码
    • 实用JavaScricpt封装
    • ES5面向对象
    • ES6面向对象
    • 多种数组去重性能对比
    • 获取ip地址
    • ES6扩展符运用
    • file、base64和blob互相转化
    • 图片转base64格式
    • 弹窗的封装
      • 任务队列管理器
        • 原理
        • 场景
        • 使用
      • 防闪烁的延迟机制
        • 原理
        • 场景
        • 使用
    • websocket实现二维码扫描
    • 比typeof运算符更准确的类型判断
    • 前端下载excel文件
    • 数组与对象的互相转化
    • JS编码与转码
    • 树结构与扁平化相互转换
    • 实现微信登录
    • 常用表单验证
    • 在H5中实现OCR拍照识别身份证功能
    • 滚动条元素定位
    • 获取目标容器内的元素列表
    • 微信H5支付
    • js中的函数注释
    • 大模型流式数据前端实现
    • 定高虚拟列表
    • 不定高虚拟列表
    • 虚拟表格
    • 移动端文件预览
    • 浏览器缓存机制
    • 前端从剪切板获取word图片
    • 微信公众号调试
    • html导出pdf
    • node转化多语言
  • 前端架构

  • 学习笔记

  • 全栈项目

  • 前端
  • JavaScript文章
夜猫子
2024-04-17
目录

弹窗的封装

# 弹窗的封装

# 任务队列管理器

# 原理

  1. 顺序执行控制
  • 确保异步任务按入队顺序执行
  • 前一个任务完成后才开始下一个
  1. 并发控制
  • 同一时间只执行一个任务
  • 后续任务在队列中等待
export class AsyncQueue {
  static create(name) {
    return new this(name);
  }

  constructor(name) {
    this.name = name;
    this.queue = [];
    this.processing = false;
  }

  async push(fun) {
    return new Promise((resolve, reject) => {
      this.queue.push({ fun, resolve, reject });
      this.process();
    });
  }

  async process() {
    if (this.processing || this.queue.length === 0) {
      return;
    }

    this.processing = true;
    const { fun, resolve, reject } = this.queue.shift();

    try {
      const result = await fun();
      resolve(result);
    } catch (error) {
      reject(error);
    } finally {
      this.processing = false;
      this.process(); // 继续处理下一个任务
    }
  }
}
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

# 场景

当触发多个弹窗时,按照触发顺序,在前一个弹窗执行完成后执行下一个弹窗。

以 uniapp 为例,先封装一个异步弹窗

// utils.js

export const promiseDialog = async (dialogProps) => {
  const {
    cancelResultType = 'resolve',
    confirmResultType = 'resolve',
    onConfirm = () => 'confirm',
    onCancel = () => 'cancel',
    ...modalProps
  } = dialogProps;

  return new Promise((resolve, reject) => {
    uni.showModal({
      ...modalProps,
      success: async (res) => {
        if (res.confirm) {
          const confirmValue = await onConfirm();
          confirmResultType === 'resolve'
            ? resolve(confirmValue)
            : reject(confirmValue);
        } else if (res.cancel) {
          const cancelValue = await onCancel();
          cancelResultType === 'resolve'
            ? resolve(cancelValue)
            : reject(cancelValue);
        }
      },
    });
  });
};
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

# 使用

import {promiseDialog,AsyncQueue} from '@/utils'
const asyncQueue = AsyncQueue.create();
await asyncQueue.push(() => {
  return promiseDialog({
    title: `promise-1`,
    onConfirm() {
      console.log('promise-1');
    },
  });
});
console.log('await promise-1');
for (let i = 0; i < 5; i++) {
  asyncQueue.push(() => {
    return promiseDialog({
      title: `task-${i}`,
    });
  });
  console.log(i);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 防闪烁的延迟机制

# 原理

  1. 计数器机制
  • loadingCount: 跟踪当前正在进行的loading请求数量
  • 避免多个请求同时控制loading状态的冲突
  1. 防抖保护
  • allowLoading: 控制是否允许显示新的loading
  • baseDelay: 设置防抖延迟时间
  • 防止loading在短时间内频繁闪烁
  1. 状态管理
正常状态: allowLoading = true  → 可以显示loading
保护状态: allowLoading = false → 暂停显示loading
1
2
export default class LoadingPanel {
  loadingCount = 0;
  baseDelay = 0;
  allowLoading = true;
  delayTimer = null;
  loadingTimeouts = new Map(); // 存储loading超时句柄
  nextId = 0; // 使用递增ID避免冲突

  constructor(delay = 0) {
    this.baseDelay = delay;
  }
    
  // 生成唯一ID
  generateId = () => {
    return `loading_${++this.nextId}`;
  };

  // 开始loading,支持超时自动清理
  addLoadingPanel = (loadingStartFn, timeout = 10000) => {
    if (!this.allowLoading) {
      return;
    }

    this.loadingCount++;
    
    if (this.loadingCount === 1) {
      loadingStartFn();
      
      // 设置超时保护,防止loading永久显示
      if (timeout > 0) {
        const loadingId = this.generateId();
        const timeoutId = setTimeout(() => {
          console.warn('Loading timeout, auto cleanup');
          this.forceCleanup();
        }, timeout);
        
        this.loadingTimeouts.set(loadingId, timeoutId);
      }
    }
  };

  // 结束loading
  decLoadingPanel = (loadingEndFn, immediately = false) => {
    if (immediately) {
      this.cleanupTimeouts();
      this.loadingCount = 0;
    } else {
      this.loadingCount = Math.max(0, this.loadingCount - 1);
    }

    if (this.loadingCount === 0) {
      loadingEndFn?.();
      this.cleanupTimeouts(); // 清理超时句柄
      this.startDelayPeriod();
    }
  };

  // 强制清理(用于超时或异常情况)
  forceCleanup = () => {
    this.loadingCount = 0;
    this.allowLoading = true;
    
    if (this.delayTimer) {
      clearTimeout(this.delayTimer);
      this.delayTimer = null;
    }
    
    this.cleanupTimeouts();
  };

  // 清理所有超时句柄
  cleanupTimeouts = () => {
    this.loadingTimeouts.forEach(timeoutId => {
      clearTimeout(timeoutId);
    });
    this.loadingTimeouts.clear();
  };

  // 启动延迟保护期
  startDelayPeriod = () => {
    if (this.baseDelay > 0) {
      this.allowLoading = false;
      
      if (this.delayTimer) {
        clearTimeout(this.delayTimer);
      }
      
      this.delayTimer = setTimeout(() => {
        this.allowLoading = true;
        this.delayTimer = null;
      }, this.baseDelay);
    }
  };
}
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

# 场景

多次连续 loading 弹窗,避免 loading 闪缩。

# 使用

const loadingPanel = new LoadingPanel(1000); // 1秒防抖

// 请求开始
loadingPanel.addLoadingPanel(() => {
  showLoading(); // 显示loading UI
});

// 请求结束
loadingPanel.decLoadingPanel(() => {
  hideLoading(); // 隐藏loading UI
});
1
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2025/10/27 10:53:52
图片转base64格式
websocket实现二维码扫描

← 图片转base64格式 websocket实现二维码扫描→

最近更新
01
H5调用微信jssdk
09-28
02
VueVirtualScroller
09-19
03
IoC 解决了什么痛点问题?
03-10
更多文章>
Copyright © 2019-2025 Study | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式