0

我试图在 Javascript 中使用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()
    
}

该函数的入口点test()将从onload具有 id 为“note”的 div 的 html 文件的正文中调用。我希望得到像a b a b a b b. 但是 Mozilla 提供 a b b b(然后挂起),而 Chrome 提供b b b b(并挂起)。任何人都可以找出我的代码的问题吗?

4

1 回答 1

0

parent.run(parent)是循环引用,会导致栈溢出。定时器是异步的,不会按顺序运行,除非为此目的构建了一个队列。

于 2012-09-10T23:29:04.910 回答