1+ import type { SelfCorrectingClock , SelfCorrectingCountdown } from "./types/common-type" ;
2+
13/**
24 * =====================
35 * =======公共函数=======
@@ -22,6 +24,7 @@ export function safeJsonParse<T>(jsonString: string, defaultValue: T): [Error |
2224 }
2325}
2426
27+
2528/**
2629 * 对敏感信息进行脱敏处理
2730 *
@@ -54,10 +57,11 @@ export function desensitize(value: string, type: "mobile" | "idcard"): string {
5457 }
5558}
5659
60+
5761/**
5862 * 模拟互斥锁(Mutex)机制,用于控制异步操作对共享资源的访问
5963 */
60- export default class Mutex {
64+ export class Mutex {
6165
6266 /**
6367 * 锁的状态:true 表示已锁定,false 表示未锁定
@@ -116,4 +120,65 @@ export default class Mutex {
116120 return this . #queue. length ;
117121 }
118122
123+ }
124+
125+ /**
126+ * 创建零漂移的自校正实时时钟
127+ * @param interval 更新间隔(毫秒),默认 1000
128+ */
129+ export function createSelfCorrectingClock (
130+ interval : number = 1000
131+ ) : SelfCorrectingClock {
132+ let currentTime : number = Date . now ( ) ;
133+ let expected : number = Date . now ( ) + interval ;
134+ let timerId : ReturnType < typeof setTimeout > ;
135+
136+ const step = ( ) : void => {
137+ const drift : number = Date . now ( ) - expected ; // 计算漂移 :contentReference[oaicite:3]{index=3}
138+ currentTime = Date . now ( ) ;
139+ expected += interval ;
140+ // 下次延迟 = 理想间隔 - 本次漂移,保证校正 :contentReference[oaicite:4]{index=4}
141+ const timeout = Math . max ( 0 , interval - drift ) ;
142+ timerId = setTimeout ( step , timeout ) ;
143+ } ;
144+
145+ timerId = setTimeout ( step , interval ) ; // 初始启动 :contentReference[oaicite:5]{index=5}
146+ return {
147+ getCurrentTime : ( ) => currentTime ,
148+ stop : ( ) => clearTimeout ( timerId ) // 内部清除,无须外部管理 :contentReference[oaicite:6]{index=6}
149+ } ;
150+ }
151+
152+
153+ /**
154+ * 创建零漂移的自校正倒计时器
155+ * @param targetTimestamp 目标时间戳(毫秒)
156+ * @param interval 更新间隔(毫秒),默认值为 1000
157+ * @returns 自校正倒计时管理器实例,包含获取剩余时间和停止定时器的方法
158+ */
159+ export function createSelfCorrectingCountdown (
160+ targetTimestamp : number ,
161+ interval : number = 1000
162+ ) : SelfCorrectingCountdown {
163+ let remaining : number = Math . max ( targetTimestamp - Date . now ( ) , 0 ) ;
164+ let expected : number = Date . now ( ) + interval ;
165+ let timerId : ReturnType < typeof setTimeout > ;
166+
167+ const step = ( ) : void => {
168+ const drift : number = Date . now ( ) - expected ;
169+ remaining = Math . max ( targetTimestamp - Date . now ( ) , 0 ) ;
170+ if ( remaining === 0 ) {
171+ return ;
172+ }
173+ expected += interval ;
174+ const timeout = Math . max ( 0 , interval - drift ) ;
175+ timerId = setTimeout ( step , timeout ) ;
176+ } ;
177+
178+ timerId = setTimeout ( step , interval ) ;
179+
180+ return {
181+ getRemainingTime : ( ) : number => remaining ,
182+ stop : ( ) : void => clearTimeout ( timerId )
183+ } ;
119184}
0 commit comments