• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2// Checks that setInterval timers keep running even when they're
3// unrefed within their callback.
4
5const common = require('../common');
6const net = require('net');
7
8let counter1 = 0;
9let counter2 = 0;
10
11// Test1 checks that clearInterval works as expected for a timer
12// unrefed within its callback: it removes the timer and its callback
13// is not called anymore. Note that the only reason why this test is
14// robust is that:
15// 1. the repeated timer it creates has a delay of 1ms
16// 2. when this test is completed, another test starts that creates a
17//    new repeated timer with the same delay (1ms)
18// 3. because of the way timers are implemented in libuv, if two
19//    repeated timers A and B are created in that order with the same
20//    delay, it is guaranteed that the first occurrence of timer A
21//    will fire before the first occurrence of timer B
22// 4. as a result, when the timer created by Test2 fired 11 times, if
23//    the timer created by Test1 hadn't been removed by clearInterval,
24//    it would have fired 11 more times, and the assertion in the
25//    process'exit event handler would fail.
26function Test1() {
27  // Server only for maintaining event loop
28  const server = net.createServer().listen(0);
29
30  const timer1 = setInterval(common.mustCall(() => {
31    timer1.unref();
32    if (counter1++ === 3) {
33      clearInterval(timer1);
34      server.close(() => {
35        Test2();
36      });
37    }
38  }, 4), 1);
39}
40
41
42// Test2 checks setInterval continues even if it is unrefed within
43// timer callback. counter2 continues to be incremented more than 11
44// until server close completed.
45function Test2() {
46  // Server only for maintaining event loop
47  const server = net.createServer().listen(0);
48
49  const timer2 = setInterval(() => {
50    timer2.unref();
51    if (counter2++ === 3)
52      server.close();
53  }, 1);
54}
55
56Test1();
57