This is the code :
// link 1 handler. This must finish in any case before link2 starts
$('#link1').click(function () {
console.log("First Handler");
setTimeout(function() {
console.log("Thread???");
}, 2000);
});
// link 2 handler. It starts only when block code of link1's handler finish
$('#link2').click(function () {
console.log("Second Handler");
});
$('#link1').click();
$('#link2').click();
clicking, in sequence, on link1 and link2, means (for what I understand) that block code of link2’s handler can’t start before link1’s handler finish (because JS is single thread, and system events is synchronous).
Well, so, why about console.log("Thread???"); that will be printed after 2sec? I see it such as a thread. Also, the behaviour it’s the same…
When the handler is fired for link1, it runs the entire function, including the setTimeout function that merely registers the function that runs your
console.log("Thread???")statement. This happens very quickly. Think of this like you would cocking a firearm. You haven’t fired, you’ve just prepared to fire and are performing a 2 second countdown.In other words, the setTimeout function does not block the execution of any other functions and (emphasis added) does not force link2 to wait. As far as link1’s handler is concerned, it did it’s job, and the JavaScript engine proceeds to execute link2’s handler, which also finishes well before your 2000ms event fires.