2

I am trying to make a small project that will allow you to visualize the various solutions of the n-queen puzzle.

One of the most difficult issues I am facing is while trying to update the board while the function responsible for finding a solution is running. In fact I can't even get the board to disappear while someone is trying to compute a new solutions set, because the UI stops responding.

What I tried doing specifically was creating and displaying a new board in the same way that I do when the computations end, but this time inside the loop that checks if a given set consists a solution or not. That would be ln:8 on my services file.

this.checkSolution = function(board) {

    //console.log("Checking if solution ", board, " is valid.");

    for (var i = 0; i < board.length; i++) {
      for (var j = i + 1; j < board.length; j++) {
        if (Math.abs(board[i] - board[j]) == Math.abs(i - j)) {
          return false;
        };
      };
    };

    //console.log("Solution valid...");
    return true;
};

A copy of the files can be found at this plunk.

Is there a way to fix this issue, and have the board update in real time showing the current solution, while the algorithm is running?

The question stated to be similar to mine, is not really of any actual help. The OP simply asks for real word cases where one would want to use Workers, and the selected answer gives links to a few tutorials on the subject, that even though interesting, did not help me resolve the issue. I on the other hand am presenting an exact case, with a working example, that presents various difficulties (at least for me). The code is located inside an angular service that is linked with one of my modules, and making it work with a thread was not possible.

ealiaj
  • 1,525
  • 1
  • 15
  • 25
  • Maybe you make the function call itself using setTimeout, passing the counter as a param. This way other stuff will run between the timeouts. – Asons Oct 25 '15 at 07:31
  • 2
    Possible duplicate of [What are the use-cases for Web Workers?](http://stackoverflow.com/questions/2773682/what-are-the-use-cases-for-web-workers) – Asons Oct 25 '15 at 07:35

1 Answers1

1

What you need is to run a heavy-load function in a separate thread. One way to do it would be HTML5 Web Workers.

The idea is that heavy calculation part runs separately and only sends messages to the main thread, which listens to those messages and handles the UI meanwhile.

A smiple example of web workers usage is available at W3Schools

And here are more robust docs MDN

CrowbarKZ
  • 1,203
  • 11
  • 18