UNPKG

2.96 kBTypeScriptView Raw
1declare type Fn<T = any> = () => T
2/**
3 * 每个单例的 id
4 *
5 * The id of a singleton
6 * */
7declare type ID = string | number
8interface PromiseOnPendingOptions {
9 id?: ID
10 /**
11 * 用于延迟 Promise 实例删除,
12 * 如果为 undefined,则在 promise 状态改变之后立即删除
13 *
14 * Used to delay the deletion of Promise instance,
15 * if it is undefined, the promise will be deleted immediately after the state changed
16 *
17 * This option will be deprecated in next version
18 * */
19 delayTime?: number
20 /**
21 * 同 delayTime
22 * 推荐使用这个属性
23 *
24 * As same as delayTime
25 * */
26 cacheTime?: number
27}
28/**
29 * @deprecated 这个方法使用多了会导致内存泄漏,建议使用 singleton 方法代替
30 * @desc 返回 id 对应的一个单例对象
31 *
32 * Return a singleton of an object(such as Promise, Function, Object...) corresponding to the id.
33 * */
34declare function singletonObj<T extends any>(id: ID, defaultValue?: () => T): T
35/**
36 * @desc 返回 id 对应的一个单例对象,这个方法应当配合返回的 delete 方法一起使用,否则使用多了会导致内存泄漏
37 *
38 * Return a singleton of an object(such as Promise, Function, Object...) corresponding to the id.
39 * This method will cause OOM if it's used too much without calling `delete`.
40 * */
41declare function singleton<T extends any>(
42 id: ID,
43 defaultValue?: () => T,
44): {
45 value: T
46 delete(): void
47 update(action: T | ((pre: T) => T)): T
48}
49/**
50 * @desc 保证一个 id 对应的 promise 在同一时间只存在一个,
51 * 并且生成 promise 的函数在 promise pending 状态的时间段内只执行一次,
52 * 这个方法可以用来减少同一时间的多余请求
53 *
54 * Ensure that only one promise corresponding to the id exists at the same time,
55 * and the function that generates the promise executes only once
56 * during the period of promise pending.
57 * This method can be used to reduce redundant requests at the same time
58 * */
59declare function promiseOnPending<P extends PromiseLike<any>>(
60 proFn: () => P,
61 options: PromiseOnPendingOptions,
62): P
63/**
64 * @desc 封装 setInterval 函数,
65 * 保证同一个 id 对应的计时器只有一个在运行,
66 * 并且返回一个清除计时器的函数,方便随时终止计时器
67 *
68 * A wrapper of the setInterval function,
69 * make sure only one timer for the same id is running,
70 * and returns a function to clear the timer so it can be terminated at any time
71 * */
72declare function runInterval(id: ID, createFn: Fn): () => void
73/**
74 * @desc 保证传入的函数在程序的运行期间只运行一次
75 *
76 * Ensure that the incoming function runs only once during the run time of the program
77 * */
78declare function onceRun(fn: Fn, id?: any): void
79
80export {
81 PromiseOnPendingOptions,
82 onceRun,
83 promiseOnPending,
84 runInterval,
85 singleton,
86 singletonObj,
87}
88
\No newline at end of file