Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the setTimeout callback on the job queue be run or cleared?

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?

like image 257
Ben Aston Avatar asked Oct 07 '15 14:10

Ben Aston


2 Answers

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:

  1. 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:

  1. Let task be a task that runs the following substeps:

    1. 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.

like image 168
James Thorpe Avatar answered Nov 14 '22 23:11

James Thorpe


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");
}
like image 37
Bartek Banachewicz Avatar answered Nov 14 '22 22:11

Bartek Banachewicz