forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useExecuteAt.ts
38 lines (32 loc) · 873 Bytes
/
useExecuteAt.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
import { useEffect } from 'react'
import { useUpdatingRef } from './useUpdatingRef'
export type UseExecuteAtOptions = {
/**
* The function to execute.
*/
fn: () => void
/**
* The date at which to execute the function. If undefined, the function will
* not fire.
*/
date: Date | undefined
}
/**
* A hook to execute a function at a specific date in the future.
*/
export const useExecuteAt = ({ fn, date }: UseExecuteAtOptions) => {
const fnRef = useUpdatingRef(fn)
useEffect(() => {
const dateTime = date?.getTime()
// Check if date defined and valid.
if (!dateTime || isNaN(dateTime)) {
return
}
const msRemaining = dateTime - Date.now()
if (msRemaining < 0) {
return
}
const timeout = setTimeout(() => fnRef.current(), msRemaining)
return () => clearTimeout(timeout)
}, [date, fnRef])
}