Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/internal/test_runner/mock/mock_timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -622,8 +622,12 @@ class MockTimers {
if (timer.runAt > this.#now) break;
FunctionPrototypeApply(timer.callback, undefined, timer.args);

this.#executionQueue.shift();
timer.priorityQueuePosition = undefined;
// Check if the timeout was cleared by calling clearTimeout inside its own callback
const afterCallback = this.#executionQueue.peek();
if (afterCallback.id === timer.id) {
this.#executionQueue.shift();
timer.priorityQueuePosition = undefined;
}

if (timer.interval !== undefined) {
timer.runAt += timer.interval;
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-runner-mock-timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,22 @@ describe('Mock Timers Test Suite', () => {
await nodeTimersPromises.setImmediate(); // let promises settle
assert.strictEqual(f2.mock.callCount(), 1);
});

it('should not affect other timers when clearing timeout inside own callback', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const f = t.mock.fn();

const timer = nodeTimers.setTimeout(() => {
f();
// Clearing the already-expired timeout should do nothing
nodeTimers.clearTimeout(timer);
}, 50);
nodeTimers.setTimeout(f, 50);
nodeTimers.setTimeout(f, 50);

t.mock.timers.runAll();
assert.strictEqual(f.mock.callCount(), 3);
});
});

describe('setInterval Suite', () => {
Expand Down