notes on javascript, linux, and more

12.22.2008

A Threading Class for Javascript: Reworked

I was playing around with my threading class for Javascript, and decided to rework it a little bit. The little research I've done indicates that as of this writing, no browser's Javascript engine implements actual threading under the hood. So, perhaps a better title for this post would be "An Asynchronous Execution Class for Javascript." Basically, you pass an array of Callback objects into the constructor for a Thread. When you call Thread.start() the sequence of callbacks are executed synchronously, from a "driver" function that is queued to run after the current call stack terminates. Not very robust, but I could see it coming in handy in some circumstances, especially involving page interactivity and event-handling.

Array.prototype.add = function(object) {
// easy way to append to an array
this[this.length] = object;
}
Callback = function(fun, args) {
this.fun = function(){
fun(args)
}
}
Thread = function (callbacks) {
/* simulates thread-like functionality for javascript
Example:
callbacks = new Array();
// an array to hold callback functions
callbacks.add( new Callback(
function(words) {
alert(words[0]+words[1])
}
,
["hello ","from callback 1"]));

callbacks.add( new Callback(
function(words) {
alert(words[0]+words[1])
}
,
["hello ","from callback 2"]));

callbacks.add( new Callback(
function(words) {
alert(words[0]+words[1])
}
,
["hello ","from callback 3"]));

callbacks.add( new Callback(
function(words) {
alert(words[0]+words[1])
}
,
["hello ","from callback 4"]));

var myThread = new Thread(callbacks);
myThread.start();
*/
this.start = function() {
var thread = function () {
for (var i=0;i<callbacks.length;i++) {
callbacks[i].fun();
}
}
setTimeout(thread,0);
// initiates the asynchronous call and returns control back to original caller
return;
}
}
Thread.sleep = function (delay){
/* simulates a Thread pause for 'delay' milliseconds
known issues:
while sleeping, browser is non-interactive
some browsers will warn the user that an infinite loop may be in progress
*/
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + delay){}
}

1 comment:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

About Me

My photo
chicago, il, United States
I'm a software engineer by profession.

Labels