Tuesday, May 15, 2012

Calling a JavaScript function "Asynchronously"

A friend of mine asked me recently how one might execute a JavaScript function "in another thread". Well, I've got good news and I've got bad news: The good news is, I understood what he was asking and you can do that. The bad news is, JavaScript isn't multi-threaded.

Calling a function (psuedo-)asynchronously in JavaScript

To kick off a function and continue on your way without waiting for that function to return, you just need to leverage setTimeout(fn, ms).


function async(fn, callback) {
    setTimeout(function() {
    }, 0);
function sync(fn) {
function foo(){

console.log('SYNC TEST --------------');
console.log('start sync');
console.log('end sync');
console.log('ASYNC TEST --------------');
console.log('start async');
async(foo, function(){ 
    console.log('async callback');
console.log('end async');


SYNC TEST --------------
start sync
end sync

ASYNC TEST --------------
start async
end async
async callback

But basic JavaScript is NOT multithreaded!

JavaScript in the browser is not going to be "multi-threaded".  JavaScript will run in a single thread, but will be executed in blocks. So it will have to finish each block of code it has queued up before continuing to the next block. This is the event loop. This can cause the illusion of "multi-threading".


  1. Wow, thank you! You have the clearest and best I've found after searching through a few sites

  2. Thank you very much it helped me a lot ...

  3. Thanks a lot... you are awesome!!!

  4. Thanks a lot for the concise explanation.

    But one thing is not clear to me,
    and in fact quite crucial for me:
    How are the code blocks determined?

    Say a function operates on the window object and erases the changes at the end
    (as in jQuery.noConflict()).
    Is there danger that another code block will be executed before the function has finished, possibly modifying the window object in between?

    We do this to allow asynchronously loading multiple versions of a library
    and providing them to multiple apps within the same page.

  5. Code blocks are determined, basically, by the function scope. So if you call function `a` that triggers two asynchronous functions `b` and `c` internally, `b` and `c` will not fire until `a` is complete. The event loop will process code blocks in the order it receives them from either setTimeout, or a client interaction such as a click, or an ajax response, etc.

    So: 1. Process global. 2. Process the next asynchronous callback. 3. Go to 2.


This form allows some basic HTML. It will only create links if you wrap the URL in an anchor tag (Sorry, it's the Blogger default)