JavaScript Async <> Multi-threaded

Upon reacquainting myself with JavaScript, I learned to love the asynchronous nature built into JavaScript. It’s just there, with no real work to do on my part.  Want something to happen later?  setTimeout.  *poof* it’s done when you want.  Want something to happen continuously?  setInterval.  *poof* that’s done too.

Now the danger of this is that Asynchronous feels like you just sent something to the background  to happen later on another thread and won’t interfere with anything you want to do.  That is not the case.  At least within the browser anyway.

JavaScript asynchronous functions just get stuck in a queue.  An ordered queue so that things can happen in the order you want, but still a queue.  Then when there is time on the main thread, the queue will be accessed to get the next function to execute.

This isn’t a problem.  I don’t mind that it works that way, but you have to be aware that it works this way. So if you have an async function that goes into an endless loop (I don’t recommend this), then it will block everything on your page.  Here is a simple test page:

<head>
<script lang="text/javascript">
  function add() {
	document.getElementById('blah').innerText += 'a';
  }
  function block() {
	while ( true ) {}
  }
</script>
</head>
<body>
  <button onclick="add()">add</button>
  <button onclick="setTimeout( block, 500 )">block</button>
  <div id="blah"></div>
</body>

You will see that you can hit the “add” button to add an ‘a’ to the screen.  But when you hit the “block” button, you will no longer be able to hid the “add” button.  At all.  The browser is too busy stuck in a loop.

Obviously, you would never put an endless loop in there on purpose, but if you have some asynchronous task that is going to take a long time to execute, then this is something you should know about.  Asynchronous is not the same as multi-threaded, so you have to be careful not to block your interface, or other tasks that may need to execute.

There is a way though.  Look up Worker Threads in JavaScript.  I haven’t actually tried this myself yet, but when I have a need to, I will.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>