views:

89

answers:

3

I have a recursive function in my JavaScript file. It looks something like this:

function process(node){
    if(someCondition)
        return someValue;
    a = process(node.children);
    b = doSomething(a);
    return b;
}

The problem is that I want to display the state of the system to the HTML output on each step of this recursion. There should be a delay between each step. (Just assume that I want to display the recursion live to the users). In any other language I would use a delay() call inside the function, but since JavaScript supports nothing other than setTimeout() to do something like this, I am lost because I don't know how to use the setTimeout call in this particular case.

Normally in simpler cases I would use something like this:

function process(node){
    if(someCondition)
        return someValue;
    setTimeout("process(node.children)", delay);
}

;but since my original function returns a value, I don't know how to proceed.

Thanks in advance.

A: 

You might try a web worker, if you're targeting HTML5.

Seth
Unfortunately, it looks like even web workers cannot solve this problem. Any ideas?
Niyaz
+1  A: 

I think this will not work as a pure recursive algorithm.

You could store the current value of b in a global variable.

You could then us setInterval to process the value in a similar way, updating the value of b on each iteration, using clearTimeout to stop execution when the condition is met.

Matt