You Are Here Home > Basic threading in JavaScript; JavaScript Worker Threads

Basic threading in JavaScript; JavaScript Worker Threads

I was searching the web yesterday for this and didn’t really find a simple way of doing this and suddenly, I remembered something.

It’s extremely simple, someone could build on it with all sorts of features but for now, here is an example:
http://images.code-head.com/code/javascript/js-threads.html

As you can see there are two counters, one is counting up and the other down simultaneously.

Here is the start_thread function:

function thread_start(callback) {
   setTimeout(callback, 1);
   return true;
}

The trick is that setTimeout *does not* block the execution and starts another thread to run the callback function :)

I hope this helps someone :)

Basic threading in JavaScript; JavaScript Worker Threads
Filed under: Fun,General,JavaScript,jQuery,Programming   Posted by: Hamid

5 Comments »

  1. Yussuf Shaikh Ibrahim:
     

    THANK YOU..m proud of u…!!! :)
    ya it helped me

    Comment

     
  2. RajaMohamed:
     

    very much thanks…. it helped me lot

    Comment

     
  3.  

    Thanks Hamid. Using the setTimeout pattern, I have created a “Threaded” non blocking object with start/stop methods…

    https://gist.github.com/676352

    Comment

     
  4. Mhmt:
     

    hi

    i’d like pass arguments to the thread function or callback. do you have any idea?

    br

    Comment

     
  5. ben:
     

    This is not threading. Javascript is single threaded (unless you use a worker). All you are doing is a very small piece of work on a timer. You will block execution doing this, you just don’t notice it because it is not doing anything intensive.

    BTW if you want to pass parameters then something like:
    setTimeout(function(){callback(parameter)}, 1);

    Comment

     

RSS feed for comments on this post. TrackBack URL

Leave a comment