-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathwait.ts
65 lines (59 loc) · 1.54 KB
/
wait.ts
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
import { tick } from './tick';
/**
* 直接条件为真或者超时才返回结果
*
* @param condition 检测条件
* @param maxTime 最大等待时长(毫秒)
*
* @returns 返回检测的结果,超时返回false
*/
export async function waitUntil(
condition: () => boolean | Promise<boolean>,
maxTime?: number
) {
// 记录检测开始时间
const start = Date.now();
// 如果检测条件不为函数,直接返回结果
if (typeof condition !== 'function') {
return !!condition;
}
// 设置默认检测时间的最大值,如果没有设置,则一直检测
if (!maxTime || typeof maxTime !== 'number') {
maxTime = Infinity;
}
return new Promise<boolean>((resolve) => {
const stop = tick(() => {
const now = Date.now();
const result = condition();
// 超时返回false
if (now - start >= maxTime!) {
stop();
resolve(false);
return;
}
// 处理结果
const handle = (res: boolean) => {
if (res) {
stop();
resolve(true);
}
};
// 未超时状态
if (result instanceof Promise) {
result.then(handle);
return;
}
// 普通一般的结果
handle(result);
});
});
}
/**
* 等待固定时间,期间一直阻塞
* @param duration 等待时长(毫秒)
*/
export async function waitFor(duration: number) {
return new Promise<void>((resolve) => {
window.setTimeout(resolve, duration);
});
}