2626import { validateFunction } from 'node-internal:validators' ;
2727import { default as timersUtil } from 'node-internal:timers' ;
2828
29+ // Capture original global timer functions at module load time, before they might be
30+ // overridden by the enable_nodejs_global_timers compat flag. This avoids circular
31+ // dependency issues when our setTimeout/setInterval return Timeout objects.
32+ // Cast to number-returning functions since we know we're capturing the original
33+ // implementations before any override.
34+ const originalSetTimeout = globalThis . setTimeout . bind ( globalThis ) as (
35+ callback : ( ...args : unknown [ ] ) => unknown ,
36+ ms ?: number ,
37+ ...args : unknown [ ]
38+ ) => number ;
39+ const originalSetInterval = globalThis . setInterval . bind ( globalThis ) as (
40+ callback : ( ...args : unknown [ ] ) => unknown ,
41+ ms ?: number ,
42+ ...args : unknown [ ]
43+ ) => number ;
44+ const originalClearTimeout = globalThis . clearTimeout . bind ( globalThis ) as (
45+ id ?: number
46+ ) => void ;
47+ const originalClearInterval = globalThis . clearInterval . bind ( globalThis ) as (
48+ id ?: number
49+ ) => void ;
50+
2951let clearTimeoutImpl : ( obj : Timeout ) => void ;
3052
3153export class Timeout {
@@ -54,18 +76,17 @@ export class Timeout {
5476 }
5577
5678 #constructTimer( ) : number {
57- // @ts -expect-error TS2322 Due to difference between Node.js and globals
5879 this . #timer = this . #isRepeat
59- ? globalThis . setInterval ( this . #callback, this . #after, ...this . #args)
60- : globalThis . setTimeout ( this . #callback, this . #after, ...this . #args) ;
80+ ? originalSetInterval ( this . #callback, this . #after, ...this . #args)
81+ : originalSetTimeout ( this . #callback, this . #after, ...this . #args) ;
6182 return this . #timer;
6283 }
6384
6485 #clearTimeout( ) : void {
6586 if ( this . #isRepeat) {
66- globalThis . clearInterval ( this . #timer) ;
87+ originalClearInterval ( this . #timer) ;
6788 } else {
68- globalThis . clearTimeout ( this . #timer) ;
89+ originalClearTimeout ( this . #timer) ;
6990 }
7091 }
7192
@@ -133,7 +154,7 @@ export function clearTimeout(
133154 if ( timer instanceof Timeout ) {
134155 clearTimeoutImpl ( timer ) ;
135156 } else if ( typeof timer === 'number' ) {
136- globalThis . clearTimeout ( timer ) ;
157+ originalClearTimeout ( timer ) ;
137158 }
138159}
139160
@@ -162,7 +183,7 @@ export function clearInterval(
162183 if ( timer instanceof Timeout ) {
163184 clearTimeoutImpl ( timer ) ;
164185 } else if ( typeof timer === 'number' ) {
165- globalThis . clearInterval ( timer ) ;
186+ originalClearInterval ( timer ) ;
166187 }
167188}
168189
@@ -182,7 +203,7 @@ export function unenroll(timer: unknown): void {
182203 if ( timer instanceof Timeout ) {
183204 clearTimeoutImpl ( timer ) ;
184205 } else if ( typeof timer === 'number' ) {
185- globalThis . clearTimeout ( timer ) ;
206+ originalClearTimeout ( timer ) ;
186207 }
187208}
188209
0 commit comments