timers.runAll()


立即触发所有待处理的模拟定时器。

🌐 Triggers all pending mocked timers immediately.

下面的示例会立即触发所有待处理的计时器,使它们无需任何延迟就执行。

🌐 The example below triggers all pending timers immediately, causing them to execute without any delay.

import assert from 'node:assert';
import { test } from 'node:test';

test('runAll functions following the given order', (context) => {
  context.mock.timers.enable(['setTimeout']);
  const results = [];
  setTimeout(() => results.push(1), 9999);

  // Notice that if both timers have the same timeout,
  // the order of execution is guaranteed
  setTimeout(() => results.push(3), 8888);
  setTimeout(() => results.push(2), 8888);

  assert.deepStrictEqual(results, []);

  context.mock.timers.runAll();

  assert.deepStrictEqual(results, [3, 2, 1]);
});const assert = require('node:assert');
const { test } = require('node:test');

test('runAll functions following the given order', (context) => {
  context.mock.timers.enable(['setTimeout']);
  const results = [];
  setTimeout(() => results.push(1), 9999);

  // Notice that if both timers have the same timeout,
  // the order of execution is guaranteed
  setTimeout(() => results.push(3), 8888);
  setTimeout(() => results.push(2), 8888);

  assert.deepStrictEqual(results, []);

  context.mock.timers.runAll();

  assert.deepStrictEqual(results, [3, 2, 1]);
});

注意: runAll() 函数专门用于在定时器模拟的环境中触发定时器。它不会对真实系统时钟或模拟环境之外的实际定时器产生任何影响。