Javascript internals - clearTimeout just before it fires

Even though Node is single thread, the race condition the question describes is possible.

It can happen because timers are triggered by native code (in lib_uv). On top of that, Node groups timers with the same timeout value. As a result, if you schedule two timers with the same timeout within the same ms, they will be added to the event queue at once.

But rest assured node internally solves that for you. Quoting code from node 0.12.0:

timer.js > clearTimeout

exports.clearTimeout = function(timer) {
  if (timer && (timer[kOnTimeout] || timer._onTimeout)) {
    timer[kOnTimeout] = timer._onTimeout = null;
    // ...
  }
}

On clearing a timeout, Node internally removes the reference to the callback function. So even if the race condition happens, it can do no harm, because those timers will be skipped:

listOnTimeout

if (!first._onTimeout) continue;

Node.js executes in a single thread.

So there cannot be any race conditions and you can reliably cancel the timeout before it triggers.

See also a related discussion (in browsers).

I am talking about a situation where the setTimeout time actually expires and the interpreter starts the process of executing it

Without having looked at Node.js internals, I don't think this is possible. Everything is single-threaded, so the interpreter cannot be "in the process" of doing anything while your code is running.

Your code has to return control before the timeout can be triggered. If you put an infinite loop in your code, the whole system hangs. This is all "cooperative multitasking".