Issue with setinterval/settimeout

I was trying to mock a simple background thread in Javascript using 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()
    
}

Entry point to the function is test() which will be called from body onload of a html file having a div with id ‘note’.
I expected to get an output like a b a b a b b.
But Mozilla is giving a b b b (and it gets hang after that)
while Chrome gives b b b b (and hangs).
Can any one figure out the issue with my code?

2 thoughts on “Issue with setinterval/settimeout”

Leave a Comment