• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Flags: --expose-internals
2
3'use strict';
4
5const common = require('../common');
6
7const { strictEqual, throws } = require('assert');
8const { setUnrefTimeout } = require('internal/timers');
9const { inspect } = require('util');
10
11// Schedule the unrefed cases first so that the later case keeps the event loop
12// active.
13
14// Every case in this test relies on implicit sorting within either Node's or
15// libuv's timers storage data structures.
16
17// unref()'d timer
18{
19  let called = false;
20  const timer = setTimeout(common.mustCall(() => {
21    called = true;
22  }), 1);
23  timer.unref();
24
25  // This relies on implicit timers handle sorting within libuv.
26
27  setTimeout(common.mustCall(() => {
28    strictEqual(called, false, 'unref()\'d timer returned before check');
29  }), 1);
30
31  strictEqual(timer.refresh(), timer);
32}
33
34// Should throw with non-functions
35{
36  [null, true, false, 0, 1, NaN, '', 'foo', {}, Symbol()].forEach((cb) => {
37    throws(
38      () => setUnrefTimeout(cb),
39      {
40        code: 'ERR_INVALID_CALLBACK',
41        message: `Callback must be a function. Received ${inspect(cb)}`
42      }
43    );
44  });
45}
46
47// unref pooled timer
48{
49  let called = false;
50  const timer = setUnrefTimeout(common.mustCall(() => {
51    called = true;
52  }), 1);
53
54  setUnrefTimeout(common.mustCall(() => {
55    strictEqual(called, false, 'unref pooled timer returned before check');
56  }), 1);
57
58  strictEqual(timer.refresh(), timer);
59}
60
61// regular timer
62{
63  let called = false;
64  const timer = setTimeout(common.mustCall(() => {
65    called = true;
66  }), 1);
67
68  setTimeout(common.mustCall(() => {
69    strictEqual(called, false, 'pooled timer returned before check');
70  }), 1);
71
72  strictEqual(timer.refresh(), timer);
73}
74
75// regular timer
76{
77  let called = false;
78  const timer = setTimeout(common.mustCall(() => {
79    if (!called) {
80      called = true;
81      process.nextTick(common.mustCall(() => {
82        timer.refresh();
83        strictEqual(timer.hasRef(), true);
84      }));
85    }
86  }, 2), 1);
87}
88
89// interval
90{
91  let called = 0;
92  const timer = setInterval(common.mustCall(() => {
93    called += 1;
94    if (called === 2) {
95      clearInterval(timer);
96    }
97  }, 2), 1);
98
99  setTimeout(common.mustCall(() => {
100    strictEqual(called, 0, 'pooled timer returned before check');
101  }), 1);
102
103  strictEqual(timer.refresh(), timer);
104}
105