Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If JavaScript is single-threaded, what is this?

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

like image 740
markzzz Avatar asked Dec 09 '22 02:12

markzzz


1 Answers

Single-threaded? Yes!! The explanation is far too comprehensive for a short answer here and has been covered before. See this fantastic article: John Resig - How JavaScript Timers Work

Edited: Because there is no exception to the "Yes!!" :-)

like image 162
devnull69 Avatar answered Dec 24 '22 08:12

devnull69