timers: fix not to close reused timer handle by shigeki · Pull Request #11646 · nodejs/node

This issue was originally reported by @darai0512 via private communication.

He found that timer.unref in setInterval callback leads the timer not to be repeated.
It can reproduced with this sample that setInterval counter1 stops at 0.

const net = require('net');
let counter1 = 0;
const server = net.createServer().listen(0);

const timer1 = setInterval(() => {
  console.log('counter1:', counter1);
  timer1.unref();
  if (counter1++ === 10)
    server.close();
}, 1);

The timer handle is reused when it is unrefed in order to avoid new
callback in beforeExit(#3407). If it is unrefed within a setInterval
callback, the reused timer handle is closed so that setInterval no
longer keep working. This fix does not close the handle in case of
setInterval.

Checklist
  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • commit message follows commit guidelines
Affected core subsystem(s)

timer

CC: @Fishrock123, @misterdjules for timer maintainer.