Tag Archives: javascript

Multithreaded coding in Javascript

Javascript is a funny old language. I like it, while at the same time finding it absolutely horrible.

I recently ported the client side of Grapple (my networking library) to Javascript, and found a problem, in that Javascript doesn’t support threads.

There’s a simple solution though, which allows you to simulate threads.

For each thread you need, ensure it has a beginning and an endpoint, probably usually in your thread’s main loop. Make that loop be its own function, and when the function gets to the end, set a timeout to call itself again at an appropriate time interval.

For example

<script language=javascript>

function thread1()
{
console.log('Thread1');
setTimeout(thread1,1000);
}

function thread2()
{
console.log('Thread2');
setTimeout(thread2,2000);
}

thread1();
thread2();

</script>

it’s as simple as that. Each loop will yield when it hits the end of the function, and come back to life with other ‘threads’ have had their turn. It also has the benefit that as it isn’t true multithreading, you don’t have to worry about mutexes, Javascript will never do two things at once, it just isn’t capable of it.