1

This is my code to run DFS on javascript, I searched and try to use setTimeout to delay each draw for 3 seconds but it won't work. Can someone show me the way to do it?

    function DFSWithDirectedGraph(v) {
        Nodes[v].visited = true;
        reDrawNode(Nodes[v].x, Nodes[v].y, Nodes[v].id, 'blue');
            for(var j = 0; j<i; j++) {
                if(Path[v][j] != undefined && Nodes[j].visited == false) {
                    drawArrow(Nodes[v].x, Nodes[v].y, Nodes[j].x, Nodes[j].y, 'blue', Path[v][j]);
                    DFSWithDirectedGraph(j);
                    if(Path[j][v] != undefined) {
                        drawArrow(Nodes[j].x, Nodes[j].y, Nodes[v].x, Nodes[v].y, 'green', Path[j][v]);
                    } else {
                        drawArrow(Nodes[j].x, Nodes[j].y, Nodes[v].x, Nodes[v].y, 'green', "");
                    }
                }
            }
  }
Gii
  • 25
  • 3
  • setTimeout is asynchronous that means it doen't pause code execution. But you can pass a callback function to setTimeout and it will be called after specified amount of time. – starikovs May 25 '15 at 15:14
  • Here's a similar question http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep – starikovs May 25 '15 at 15:18

2 Answers2

0
setTimeout(function () { ...your code... }, time_in_milliseconds);

Note that in order to repeatedly call a function after say T milliseconds,

function f(params) {
    ... do your work ...
    id = setTimeout(f, T);
}

f(actual_params);

This will call the function f after every T milliseconds. You can remove the timeout using clearTimeout.

clearTimeout(id); // id returned from the setTimeout function
Khalid
  • 4,730
  • 5
  • 27
  • 50
a_pradhan
  • 3,285
  • 1
  • 18
  • 23
0

You should use a different type of loop if you want to accomplish this. A for loop won't pause between each time it loops.

I would do something like this:

var counter = 0;
function step(){
     //Do your loop code here
     counter++;
     if(counter >= {{length of loop}}){
          endLoop();
     }else{
         setTimeout(step, 3000);
     }
}

step();
  • somehow, it messes up my draw sequences. Can you help me to trigger draw event with the same sequences? – Gii May 25 '15 at 16:32