WebWorkers aside, the JavaScript programming model in the browser is purely single-threaded. You can make your call somewhat asynchronous by using window.setTimeout:
window.setTimeout(doSomething, 0, myCallBack);
This effectively places the call doSomething(myCallBack)
onto the timer queue, and after 0 or more milliseconds elapse, it will eventually get invoked. However, as with all asynchronous calls in JavaScript, you must relinquish the execution context before any asynchronous callbacks can be invoked; that is, the timer queue will not be processed (and therefore doSomething(myCallBack)
will not be invoked) until your main()
function finishes, assuming that is the end of your JavaScript.
One unfortunate consequence of this setTimeout
-based approach is that doSomething(myCallBack)
doesn't get invoked in parallel alongside console.log("step 4")
. On the other hand, consider XMLHttpRequest.send; after making this call, the rest of your JS can continue to execute while the browser issues the HTTP request. Your script does need to finish executing before the onreadystatechange handler can execute, but most of the HTTP connection work can happen in parallel while JS executes.