0
我想在java腳本中使用settimeout模擬一個簡單的後臺線程。問題setinterval/settimeout
function ThreadManager(timer){
var threadID=1;
if(timer)
this.frequency=timer;
else
this.frequency=10;
}
ThreadManager.prototype.frequency;
ThreadManager.prototype.process;
ThreadManager.prototype.kill;
ThreadManager.prototype.add=function(thread)
{
this.process=new Process(thread,this.threadID++);
}
ThreadManager.prototype.run=function(parent)
{
if(!parent)
parent=this;
try{
var st=parent.process.getNextStatement();
if(st==null){
if(parent.kill)
clearInterval(parent.kill)
return;
}
else
eval(st.trim());
}
catch(err)
{
console.error(err);
}
if(st!=null&&!parent.kill)
{
parent.kill=setInterval(function(){parent.run(parent)},parent.frequency);
}
}
function Process(fun,id)
{
statements=getStatements(fun);
var threadID=id;
function getStatements(fun)
{
if(!fun)
{
return statements;
}
var functionString=(""+fun).trim();
var start=functionString.indexOf("{");
functionString=functionString.substring(start,functionString.length-1);
var regx=new RegExp("[\n;]");
return functionString.split(regx);
}
}
Process.prototype.statements;
Process.prototype.getNextStatement=function()
{
var cursor=statements.pop();;
while(cursor==null||cursor==""||cursor=='}'||cursor=="{")
cursor=statements.pop();
return cursor;
}
function write(text)
{
doc=document.getElementById("note");
note.innerHTML+=text+"<br\>"
}
function f1()
{
write("a");
write("a");
write("a");
}
function f2()
{
write("b");
write("b");
write("b");
write("b");
}
function test()
{
write("hii");
var thread=new ThreadManager(500);
thread.add(f1);
thread.run();
var thread2=new ThreadManager(500);
thread2.add(f2);
thread2.run()
}
入口點函數試驗(+),將來自具有與ID爲「音符」一個div一個html文件的身體onload事件被調用。我期望得到像b a b a b b這樣的輸出。 但Mozilla給出了一個b b b(並在此之後得到掛起) 而鉻給b b b b(和掛起)。 任何人都可以找出我的代碼的問題?