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