-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
53 lines (49 loc) · 1.14 KB
/
Copy pathindex.ts
File metadata and controls
53 lines (49 loc) · 1.14 KB
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useRef, useEffect } from 'react'
// fork from koa-compose
function compose(middleware: Function[]) {
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function (context: any, next: any): any {
// last called middleware #
let index = -1
function dispatch(i: number): any {
if (i <= index) return
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if (!fn) return
try {
return fn(context, dispatch.bind(null, i + 1))
} catch (err) {
return
}
}
return dispatch(0)
}
}
export default function useTimeLineTask(
middleware: Function[],
delay: number
): void {
const savedCallback = useRef<any>()
// 保存新回调
useEffect(() => {
savedCallback.current = compose(middleware)
})
// 建立 interval
useEffect(() => {
function tick(): void {
savedCallback.current({})
}
if (delay !== null) {
const id = setInterval(tick, delay)
return (): void => {
clearInterval(id)
}
}
}, [delay])
}