0

I want to create a project in which all possible paths from (0,0) to (m-1,n-1) in a maze is found using backtracking. And I want to visualize it using javascript.
I have created a grid with grey square on which we can travel and black squares are obstacle.
I have created recursive function for it.
Now I will color and uncolor each square when I visit on it but I want to add some delay so that we can see it happening.

I tried setTimeout(), sleep() but nothing seems to work. When I use settimeout in console all the paths are printed and then after sometime all sleep !s message are printed.
They must have been printed in order of execution the function line by line.
Can I get to know how can I do it?

function is for getting path is

// maze is matrix of size mxn with value 1 as obstacle square, and 0 free to visit path
// visited matrix of size mxn keeps track of which squared we visited as not to make endless loops

let getMazePath = (maze, r, c, ans) => {
  if (
    r < 0 ||
    c < 0 ||
    r >= maze.length ||
    c >= maze[0].length ||
    maze[r][c] == 1 ||
    visited[r][c] == 1
  )
    return;

  if (r == maze.length - 1 && c == maze[0].length - 1) {
    document.getElementById("path-display").innerHTML =
      "Path is: '" + ans + "'";
    console.log("Path is: '" + ans + "'");
    return;
  }

  let currSq = document.getElementById(r + "_" + c);
  currSq.classList.add("visited-square");
  setTimeout(()=>{console.log("sleep 1s"}, 1000);

  visited[r][c] = 1;

  getMazePath(maze, r - 1, c, ans + "t");
  getMazePath(maze, r, c - 1, ans + "l");
  getMazePath(maze, r + 1, c, ans + "d");
  getMazePath(maze, r, c + 1, ans + "r");

  lol_is_statemet_is_just_to_give_a_pause;

  visited[r][c] = 0;
  setTimeout(()=>{console.log("sleep 1s"}, 1000);

  currSq.classList.remove("visited-square");
};

VIEW WHOLE CODE HERE

sachuverma
  • 559
  • 6
  • 27
  • 2
    you said you wanted to use setTimeout, can you show us how you did it? because it's most likely that you used it incorrectly – Krzysztof Krzeszewski Sep 16 '20 at 08:08
  • 1
    `let getMazePath = async (.....` ... and `await new Promise(resolve => setTimeout(resolve, 1000))` instead of `sleep` – Jaromanda X Sep 16 '20 at 08:10
  • 1
    or ... `const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); and use `await sleep(1000)` ... again, the containing function must be `async` – Jaromanda X Sep 16 '20 at 08:13
  • I used `setTimeout(()=>console.log("sleep 1s"), 1000)`. At the places where I commented out `sleep(1000)`. When I ran it, in console I can only see **path printing** not any **sleep 1s** line – sachuverma Sep 16 '20 at 09:01

0 Answers0