From 1dfcd171d2a9953e5823c8a1f538904842c4aa56 Mon Sep 17 00:00:00 2001 From: JiaLiPassion Date: Sun, 25 Feb 2024 00:43:40 +0000 Subject: [PATCH] fix(zone.js): make sure fakeasync use the same id pool with native Close #54323 fakeAsync should use the same timerId pool with native, so they will not conflict. --- .../zone.js/lib/zone-spec/fake-async-test.ts | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/zone.js/lib/zone-spec/fake-async-test.ts b/packages/zone.js/lib/zone-spec/fake-async-test.ts index e5fa1da7370630..a2215ddede06ee 100644 --- a/packages/zone.js/lib/zone-spec/fake-async-test.ts +++ b/packages/zone.js/lib/zone-spec/fake-async-test.ts @@ -61,12 +61,17 @@ const timers = { setTimeout: global.setTimeout, setInterval: global.setInterval, clearTimeout: global.clearTimeout, - clearInterval: global.clearInterval + clearInterval: global.clearInterval, + nativeSetTimeout: (global.setTimeout as any)[Zone.__symbol__('OriginalDelegate')], + nativeClearTimeout: (global.clearTimeout as any)[Zone.__symbol__('OriginalDelegate')], }; +const timeoutCallback = function() {}; + class Scheduler { // Next scheduler id. - public static nextId: number = 1; + public static nextNodeJSId: number = 1; + public static nextId: number = Scheduler.getNextId(); // Scheduler queue with the tuple of end time and callback function - sorted by end time. private _schedulerQueue: ScheduledFunction[] = []; @@ -79,6 +84,17 @@ class Scheduler { constructor() {} + static getNextId() { + const id = timers.nativeSetTimeout.call(global, timeoutCallback); + timers.nativeClearTimeout.call(global, id); + if (typeof id === 'number') { + return id; + } + // in NodeJS, we just use a number for fakeAsync, since it will not + // conflict with native TimeoutId + return Scheduler.nextNodeJSId++; + } + getCurrentTickTime() { return this._currentTickTime; } @@ -112,7 +128,8 @@ class Scheduler { }, ...options }; - let currentId = options.id! < 0 ? Scheduler.nextId++ : options.id!; + let currentId = options.id! < 0 ? Scheduler.nextId : options.id!; + Scheduler.nextId = Scheduler.getNextId(); let endTime = this._currentTickTime + delay; // Insert so that scheduler queue remains sorted by end time.