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).
JS
function async(fn, callback) { setTimeout(function() { fn(); callback(); }, 0); } function sync(fn) { fn(); } function foo(){ console.log('foo'); } console.log('SYNC TEST --------------'); //synchronous console.log('start sync'); sync(foo); console.log('end sync'); console.log(''); console.log('ASYNC TEST --------------'); //asynchronous console.log('start async'); async(foo, function(){ console.log('async callback'); }); console.log('end async');
Output
SYNC TEST -------------- start sync foo end sync ASYNC TEST -------------- start async end async foo 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".
Wow, thank you! You have the clearest and best I've found after searching through a few sites
ReplyDeleteThank you very much it helped me a lot ...
ReplyDeleteThanks a lot... you are awesome!!!
ReplyDeleteThanks a lot for the concise explanation.
ReplyDeleteBut 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.
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.
ReplyDeleteSo: 1. Process global. 2. Process the next asynchronous callback. 3. Go to 2.