@@ -58,23 +58,35 @@ export function clearTimeout(id: number): void {
58
58
}
59
59
60
60
export function setInterval ( callback : Function , milliseconds = 0 , ...args ) : number {
61
- // Cast to Number
62
61
milliseconds += 0 ;
63
62
64
63
const id = createHandlerAndGetId ( ) ;
65
64
const handler = timeoutHandler ;
66
65
const invoke = ( ) => callback ( ...args ) ;
67
66
const zoneBound = zonedCallback ( invoke ) ;
68
- const startOffset = milliseconds > 0 ? Date . now ( ) % milliseconds : 0 ;
69
- function nextCallMs ( ) {
70
- return milliseconds > 0 ? milliseconds - ( ( Date . now ( ) - startOffset ) % milliseconds ) : milliseconds ;
71
- }
67
+ let nextDueTime = Date . now ( ) + milliseconds ;
72
68
73
69
const runnable = new java . lang . Runnable ( {
74
70
run : ( ) => {
71
+ const executionStart = Date . now ( ) ;
75
72
zoneBound ( ) ;
73
+
76
74
if ( timeoutCallbacks [ id ] ) {
77
- handler . postDelayed ( runnable , long ( nextCallMs ( ) ) ) ;
75
+ const executionTime = Date . now ( ) - executionStart ;
76
+
77
+ // Update the next due time based on when this callback was supposed to execute
78
+ nextDueTime += milliseconds ;
79
+
80
+ // If the callback took longer than the interval, skip ahead to avoid catch-up
81
+ const now = Date . now ( ) ;
82
+ if ( nextDueTime <= now ) {
83
+ // Calculate how many intervals we should skip
84
+ const missedIntervals = Math . floor ( ( now - nextDueTime ) / milliseconds ) ;
85
+ nextDueTime += ( missedIntervals + 1 ) * milliseconds ;
86
+ }
87
+
88
+ const delay = Math . max ( 0 , nextDueTime - now ) ;
89
+ handler . postDelayed ( runnable , long ( delay ) ) ;
78
90
}
79
91
} ,
80
92
} ) ;
@@ -84,8 +96,7 @@ export function setInterval(callback: Function, milliseconds = 0, ...args): numb
84
96
timeoutCallbacksCb [ id ] = callback ;
85
97
}
86
98
87
- timeoutHandler . postDelayed ( runnable , long ( nextCallMs ( ) ) ) ;
88
-
99
+ handler . postDelayed ( runnable , long ( milliseconds ) ) ;
89
100
return id ;
90
101
}
91
102
0 commit comments