Asynchronous doesn't mean multithread. Javascript is event based, functions will be called when something happens (an event occurs). The event listening function is not executed on a separate thread, its just planned to be executed later.
But there one old technique to emulate multithread without the browser support for Web Workers. It's splitting up one whole task into deferring small tasks.
For example, you write this which will cause blocking:
for (var i = 0; i < 10000000; i++) {
// do something very slow
}
Turn it to this, and it will execute parallel, almost like multithreaded.
(function step(i) {
if (i < 10000000) {
// do something very slow
setTimeout(function() {step(i + 1)}, 1);
}
})(0);
Edit: I just realized that this will cause memory problem, because in each step closure we are referencing the previous step, making it impossible for the GC to clean up memory. To overcome this, put i
out of the arguments, and change it like this (I'm wrapping the whole thing with a function, so that i
can not be changed mistakenly outside):
(function() {
var i = 0;
(function step() {
if (i < 10000000) {
// do something very slow
i++;
setTimeout(step, 1);
}
})();
})();