There is a code:

/*Присваиваем метки*/ let label = 0; function setLabel(y, x) { setTimeout(function() { matrix[y][x].label = label; setDivLabel(y, x, label); console.log(matrix[y][x].label); label = label + 1; if (validCell(y - 1, x) && checkCell(matrix[y - 1][x])) { setLabel(y - 1, x); } if (validCell(y + 1, x) && checkCell(matrix[y + 1][x])) { setLabel(y + 1, x); } if (validCell(y, x - 1) && checkCell(matrix[y][x - 1])) { setLabel(y, x - 1); } if (validCell(y, x + 1) && checkCell(matrix[y][x + 1])) { setLabel(y, x + 1); } label = label - 1; }, 500); } setLabel(io.enter[0], io.enter[1]); 

When performing the label at each iteration of 0. Why so, please tell me?

  • else if ? .... - meine
  • If I put the else if, then reaching the wall, I will not come back. 82.179.51.71 - server address, this is my coursework. This code is an implementation of the path search trace algorithm (aTrace.js). - Kolobok163rus
  • @Igor, maybe :-) - Grundy

1 answer 1

The problem is the asynchrony of the setLabel function.

Specifically, the problem is in the string

 label = label - 1; 

Which is executed before the setLabel functions are setLabel inside the conditions.

Because of this, after exiting a function and moving to the next, the label value does not change.

You can solve this by saving the label to a local variable before calling setTimeout

Either pass the current label value as a parameter, rather than using a global variable.

  • Thank you, passed as a parameter. It all worked. - Kolobok163rus