Global and Local Variables in JavaScript
Mar 03

Hello, Today I’m going to explain how you can simulate threads in JavaScript, because JavaScript doesn’t have an explicit thread object, like C# or Java does. But it does have 2(two) methods (setTimeout and setInterval) that you can use in order to get at least some of the basic behaviours of threads. You don’t have all the features like: sleep, suspend, resume and some others, but you can specify when is going to start and end, with just these 2(two) I guaranty you can do a lot.

Part 1

You might ask why use threads or even why do I need something like that for a web application, well we know that nowadays the users have better computers that can handle more process, but we cannot count on that and have to consider that a big process can freezes the user’s interface, which for sure will frustrate them. So that’s exactly when threads become hand when you have a task that might take a long time to finish and doing that it could freezes the user’s interface. So what you need is somehow put this long process in another thread, which will not interfere with the thread that is taking care of the user’s interface.

Part 2

On the “default.aspx” page:

<table>
  <tr>
   
<td colspan=”2″ style=”text-align: center”>
      <input onclick=”Stop();” type=”button” value=”Stop”/>
    </
td>
 
</tr>
  <tr>
   
<td>
      <textarea cols=”50″ name=”textarea1″ rows=”20″></textarea>
    </td>
 
</tr>
  <tr>
   
<td style=”text-align: center”>
<input onclick=”BigLoop1();” type=”button” value=”Big loop 1″/>
<input onclick=”ExecsetTimeout1();” type=”button” value=”setTimeout 1″/>
<input onclick=”ExecsetInterval1();” type=”button” value=”setInterval 1″/>
    </td>
  </tr>
</table>

On the “How-to-Simulate-Threads-in-JavaScript.js” file:

// Big Loop
function BigLoop1()
{
  document.form1.textarea1.value = “”;
  for (var I = 0; I < 10000; I++)
   
document.form1.textarea1.value += Text;
}

// Global Variables
var IdsetTimeout1 = null;
var IdInterval1 = null;
var Text = “a”;

// setTimeout
function ExecsetTimeout1()
{
 
IdsetTimeout1 = setTimeout(ExecsetTimeout3, 100);
}

function ExecsetTimeout3()
{
  document.form1.textarea1.value += Text;
 
ExecsetTimeout1();
}

// setInterval
function ExecsetInterval1()
{
  clearInterval(IdInterval1);
  IdInterval1 = setInterval(ExecsetInterval3, 100);
}

function ExecsetInterval3()
{
  document.form1.textarea1.value += Text;
}

// Clear the timers.
function Stop()
{
  clearTimeout(IdsetTimeout1);
  clearInterval(IdInterval1);
}

References:

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

To download the code, click here -> How to Simulate threads in JavaScript

Author: Luciano Sampaio

Leave a Reply