1'use strict';
2
3// https://github.com/nodejs/node/issues/3020
4// Promises, nextTick, and queueMicrotask allow code to escape the timeout
5// set for runInContext, runInNewContext, and runInThisContext
6
7const common = require('../common');
8const assert = require('assert');
9const vm = require('vm');
10
11const NS_PER_MS = 1000000n;
12
13const hrtime = process.hrtime.bigint;
14
15const loopDuration = common.platformTimeout(1000n);
16const timeout = common.platformTimeout(100);
17
18function loop() {
19  const start = hrtime();
20  while (1) {
21    const current = hrtime();
22    const span = (current - start) / NS_PER_MS;
23    if (span >= loopDuration) {
24      throw new Error(
25        `escaped ${timeout}ms timeout at ${span}ms`);
26    }
27  }
28}
29
30assert.throws(() => {
31  vm.runInNewContext(
32    'queueMicrotask(loop); loop();',
33    {
34      hrtime,
35      queueMicrotask,
36      loop,
37    },
38    { timeout, microtaskMode: 'afterScriptRun' },
39  );
40}, {
41  code: 'ERR_SCRIPT_EXECUTION_TIMEOUT',
42  message: `Script execution timed out after ${timeout}ms`,
43});
44