home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Minami 80
/
MINAMI80.iso
/
Extra
/
DivXInstaller.exe
/
$PLUGINSDIR
/
GoogleToolbarFirefox.msi
/
xpi
/
amulet-jslib
/
google3
/
thread-queue.js
< prev
Wrap
Text File
|
2006-05-15
|
3KB
|
85 lines
function TH_ThreadQueue(opt_config) {
this.runtime_ = 100;
this.delay_ = 25;
this.interleave_ = true;
if (opt_config) {
this.interleave_ = (opt_config.interleave === true);
if (opt_config.runtime) this.runtime_ = opt_config.runtime;
if (opt_config.delay) this.delay_ = opt_config.delay;
}
this.workers_ = [];
this.guid_ = 0;
this.iterate_ = Function.prototype.bind.call(this.runIteration_, this);
}
TH_ThreadQueue.prototype.addWorker = function(worker, opt_isComplete) {
if (worker.__workerId) {
throw new Error("Cannot add a worker to a thread while it is currently " +
"running in the thread.");
}
worker.__isComplete = opt_isComplete || function() { return false; };
worker.__workerId = this.guid_++;
this.workers_.push(worker);
if (this.workers_.length == 1) {
this.setCurrentWorkerByIndex_(0);
this.iterate_();
}
}
TH_ThreadQueue.prototype.removeWorker = function(worker) {
for (var i = 0; i < this.workers_.length; i++) {
if (worker.__workerId == this.workers_[i].__workerId) {
this.removeWorkerByIndex_(i);
}
}
}
TH_ThreadQueue.prototype.removeWorkerByIndex_ = function(workerIndex) {
var worker = this.workers_[workerIndex];
delete(worker.__isComplete);
delete(worker.__workerId);
this.workers_.splice(workerIndex, 1);
var newWorkerIndex = this.currentWorkerIndex_ % this.workers_.length;
this.setCurrentWorkerByIndex_(newWorkerIndex);
}
TH_ThreadQueue.prototype.setDelay = function(delay) {
this.delay_ = delay;
}
TH_ThreadQueue.prototype.setRuntime = function(runtime) {
this.runtime_ = runtime;
}
TH_ThreadQueue.prototype.run = function() {
this.running_ = true;
this.iterate_();
}
TH_ThreadQueue.prototype.pause = function() {
this.running_ = false;
}
TH_ThreadQueue.prototype.runIteration_ = function() {
if (!this.running_ || this.workers_.length == 0) {
return;
}
var startTime = (new Date()).getTime();
while ((new Date()).getTime() - startTime < this.runtime_) {
if (this.currentWorker_.__isComplete()) {
this.removeWorkerByIndex_(this.currentWorkerIndex_);
break;
}
this.currentWorker_();
if (this.interleave_) this.nextWorker_();
}
if (typeof top != "undefined" && top.setTimeout) {
top.setTimeout(this.iterate_, this.delay_);
} else if (G_Alarm) {
new G_Alarm(this.iterate_, this.delay_);
} else {
throw new Error("Could not find a mechanism to start a timeout. Need " +
"window.setTimeout or G_Alarm.");
}
}
TH_ThreadQueue.prototype.setCurrentWorkerByIndex_ = function(workerIndex) {
this.currentWorkerIndex_ = workerIndex;
this.currentWorker_ = this.workers_[workerIndex];
}
TH_ThreadQueue.prototype.nextWorker_ = function() {
var nextWorkerIndex = (this.currentWorkerIndex_ + 1) % this.workers_.length;
this.setCurrentWorkerByIndex_(nextWorkerIndex);
}