Pseudothreading (pseudo-threading)

Pseudothreading is a programming technique for JavaScript that emulates threading. It's done using setTimeouted function calls. Pseudo-threading is a workaround for absence of real threading/concurrency with access to DOM (Document Object Model) in client side (browser) JavaScript.

How does it work?

In JavaScript, it's possible to delay the code execution using two important functions, setTimeout and setInterval. It's possible to create some function, that gets called from setTimeout callback, that is inside such function. I call it recursion with delay. Let me show minimal example for that:


function pseudoThread(){
  //code...
  setTimeout(function(){pseudoThread();},1);
}
pseudoThread();

This example simply runs forever and does nothing. It's just a "pattern". The minimal implementation of pseudo-threading.


Unlike web workers, this solution can access DOM. DOM is actual model of the website downloaded into browser. So let's extend our minimal example:


<div id="someDiv">
</div>
<script>
function pseudoThread(){
  document.getElementById("someDiv").innerHTML+=".";
  setTimeout(function(){pseudoThread();},1);
}
pseudoThread();
</script>

This example adds dots into someDiv as quickly as possible, but without blocking of the browser GUI (Graphical User Interface).


Now, let's extend the example even more, we need dots and commas as quickly as possible.

<div id="someDiv">
</div>
<script>
function pseudoThread1(){
  document.getElementById("someDiv").innerHTML+=".";
  setTimeout(function(){pseudoThread1();},1);
}
function pseudoThread2(){
  document.getElementById("someDiv").innerHTML+=",";
  setTimeout(function(){pseudoThread2();},1);
}
pseudoThread1();
pseudoThread2();
</script>

This example adds dots and commas into someDiv as quickly as possible, but without blocking of the browser GUI (Graphical User Interface). It looks like those function calls run parallelly, so function declarations are like threads declarations in other programming languages. That's why I call them pseudothreads. It looks like it's parallel, but it isn't. So PSEUDO...


Extending this principle with functionality (like wrapping of this code with JavaScript module pattern, adding time measuring, context switching, ...), I've created MOOPH module. Look at MOOPH.EU for more info.

© 2018 Čeněk Svoboda