Lucky
Lucky

Reputation: 241

What's the internal difference between async and multithreading?

I used to consider async as equavelent as multithreading. Multi tasks will be done parallel. However, in javascript I wrote this and it seems that dosomething will never happen.

setTimeout(1000, dosomething)
while(true){}

Why?

Upvotes: 0

Views: 65

Answers (2)

Andy Brown
Andy Brown

Reputation: 12999

Multithreading is one of many ways to implement asynchronous programming. Reacting to events and yielding to a scheduler is one other way, and happens to be the way that javascript in the browser is implemented.

In your example, the event that gave you control and allowed you to call setTimeout must be allowed to complete so that the javascript engine can monitor the timeout and call your doSomething callback when it expires.

Upvotes: 0

mickadoo
mickadoo

Reputation: 3483

Node.js is a single threaded asynchronous language. As mentioned in another answer

Javascript is single threaded (with the exception of web workers, but that is irrelavent to this example so we will ignore it). What this means is that setTimeout actually does is schedules some code to be executed some time in the future, after at least some amount of time, but only when the browser has stopped whatever else it was doing on the rendering thread at the time, which could be rendering html, or executing javascript.

In your example the execution of the while loop never stops, control is never returned to the top level, so the scheduled setTimeout function is never executed.

Upvotes: 1

Related Questions