@@ -51,8 +51,45 @@ export function getDeadlineTimeoutString(deadline: Deadline) {
5151 throw new Error ( 'Deadline is too far in the future' )
5252}
5353
54+ /**
55+ * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args
56+ * In particular, "When delay is larger than 2147483647 or less than 1, the
57+ * delay will be set to 1. Non-integer delays are truncated to an integer."
58+ * This number of milliseconds is almost 25 days.
59+ */
60+ const MAX_TIMEOUT_TIME = 2147483647 ;
61+
62+ /**
63+ * Get the timeout value that should be passed to setTimeout now for the timer
64+ * to end at the deadline. For any deadline before now, the timer should end
65+ * immediately, represented by a value of 0. For any deadline more than
66+ * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will
67+ * end at that time, so it is treated as infinitely far in the future.
68+ * @param deadline
69+ * @returns
70+ */
5471export function getRelativeTimeout ( deadline : Deadline ) {
5572 const deadlineMs = deadline instanceof Date ? deadline . getTime ( ) : deadline ;
5673 const now = new Date ( ) . getTime ( ) ;
57- return deadlineMs - now ;
74+ const timeout = deadlineMs - now ;
75+ if ( timeout < 0 ) {
76+ return 0 ;
77+ } else if ( timeout > MAX_TIMEOUT_TIME ) {
78+ return Infinity
79+ } else {
80+ return timeout ;
81+ }
82+ }
83+
84+ export function deadlineToString ( deadline : Deadline ) : string {
85+ if ( deadline instanceof Date ) {
86+ return deadline . toISOString ( ) ;
87+ } else {
88+ const dateDeadline = new Date ( deadline ) ;
89+ if ( Number . isNaN ( dateDeadline . getTime ( ) ) ) {
90+ return '' + deadline ;
91+ } else {
92+ return dateDeadline . toISOString ( ) ;
93+ }
94+ }
5895}
0 commit comments