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() 函数是专门为在定时器模拟上下文中触发定时器而设计的。它对模拟环境之外的实时系统时钟或实际定时器没有任何影响。

¥Note: The runAll() function is specifically designed for triggering timers in the context of timer mocking. It does not have any effect on real-time system clocks or actual timers outside of the mocking environment.