Skip to content

Commit

Permalink
fix(zone.js): make sure fakeasync use the same id pool with native (#…
Browse files Browse the repository at this point in the history
…54600)

Close #54323

fakeAsync should use the same timerId pool with native, so they will not
conflict.

PR Close #54600
  • Loading branch information
JiaLiPassion authored and dylhunn committed Mar 28, 2024
1 parent 6d14fc5 commit ddbf6bb
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions packages/zone.js/lib/zone-spec/fake-async-test.ts
Expand Up @@ -66,11 +66,16 @@ let patchedTimers: {
setInterval: typeof setInterval,
clearTimeout: typeof clearTimeout,
clearInterval: typeof clearInterval,
nativeSetTimeout: typeof setTimeout,
nativeClearTimeout: typeof clearTimeout,
}|undefined;

const timeoutCallback = function() {};

class Scheduler {
// Next scheduler id.
public static nextId: number = 1;
public static nextNodeJSId: number = 1;
public static nextId: number = -1;

// Scheduler queue with the tuple of end time and callback function - sorted by end time.
private _schedulerQueue: ScheduledFunction[] = [];
Expand All @@ -83,6 +88,17 @@ class Scheduler {

constructor() {}

static getNextId() {
const id = patchedTimers!.nativeSetTimeout.call(global, timeoutCallback, 0);
patchedTimers!.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;
}
Expand Down Expand Up @@ -116,7 +132,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.
Expand Down Expand Up @@ -877,6 +894,10 @@ export function patchFakeAsyncTest(Zone: ZoneType): void {
setTimeout: global.setTimeout,
setInterval: global.setInterval,
clearTimeout: global.clearTimeout,
clearInterval: global.clearInterval
clearInterval: global.clearInterval,
nativeSetTimeout: global[Zone.__symbol__('setTimeout')],
nativeClearTimeout: global[Zone.__symbol__('clearTimeout')],
};

Scheduler.nextId = Scheduler.getNextId();
}

0 comments on commit ddbf6bb

Please sign in to comment.