Javascript code is asynchronous when it calls a function that's asynchronous.
So, what makes a function asynchronous?
A javascript function is asynchronous when it calls an asynchronous function:
function myAsyncFunction (callback) {
setTimeout(function(){callback()}, 100);
}
So, how does setTimeout
or element.onchange
get implemented?
They're implemented in C.
For general-purpose background processing, setTimeout
and setInterval
is the lowest-level interface to the event loop that javascript gives you. So to implement your own asynchronous functions in pure javascript you need to use setTimeout
.
For example, if we take your original code we can make it asynchronous by simply doing this:
var a = function(str,callback) {
setTimeout(function() {
console.log('This should be first: ' + str + '.')
},1000);
setTimeout(callback,1001);
}
For functionality that need to process in other ways, for example run another thread or read a file or query a database, you can't do it in pure javascript. You need to modify the browser code in C. Different browsers have different ways for you to do this "officially" with plugins (that's how things like Flash and Java gets implemented). Some browsers don't allow you to do this at all.
Node.js allows you to write modules in C using the Addon API: http://nodejs.org/api/addons.html. From there on, how you make your code asynchronous is up to you - threads, select, epoll etc. But you are responsible for interfacing with the javascript event loop (most probably implemented using select/poll/epoll so you don't need to create your own).