If the callback for a setTimeout
invocation is added to the job queue (for example, if it is next on the job queue), and a clearTimeout
is called on the current tick of the event loop, supplying the id
of the original setTimeout
invocation. Will the setTimeout
callback on the job queue be run?
Or does the runtime magically remove the callback from the job queue?
No, it won't run; it will be queued and then subsequently aborted. The specificiation goes through a number of steps when you call setTimeout
, one of which (after the minimum timeout, plus and user-agent padded timeouts etc) is eventually:
- Queue the task task.
This appears to happen regardless of whether or not the handle that was returned in step 10 has been cleared - ie a call to setTimeout
will always result in something being enqueued.
When you call clearTimeout
, it:
must clear the entry identified as handle from the list of active timers
ie it doesn't directly affect the process already kicked off in the call to setTimeout
. Note however that further up that process, task has been defined as:
Let task be a task that runs the following substeps:
- If the entry for handle in the list of active timers has been cleared, then abort this task's substeps.
So when the task begins executing, it will first check if the handle has been cleared.
No, it won't be ran.
I don't know which source should be used to back it up officially, but it's at least easy to try for yourself.
function f() {
var t1 = setTimeout(function() { console.log("YES"); }, 2000);
sleep(3000);
clearTimeout(t1);
console.log("NO");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With