First I want to say that I've read several answers regarding this issues like:
JavaScript : For loop with timeout
Delay each iteration of loop by a certain time
and some others but I just can't figure it out how exactly this works.
So after some experiments I end up with those two functions:
function searchForPathWithDelay() {
var isPathFound = false;
for (var i = 0; i < cells.length; i = i + 1) {
if (isThisTheGoalNode(cells[i].axisX, cells[i].axisY)) {
//the below should be in own method
var selectedNode = document.querySelector('[data-cellNumber="' + cells[i].id + '"]');
selectedNode.style.backgroundColor = 'red';
break;
}
setTimeout(searchForPath(cells[i].axisX, cells[i].axisY, cells[i].id), 500);
}
}
and then:
function searchForPath(axisX, axisY, id) {
if (isCellInBoundries(axisX, axisY)) {
var selectedNode = document.querySelector('[data-cellNumber="' + id + '"]');
selectedNode.style.backgroundColor = 'green';
}
}
Since it's just a fun thing that I'm doing but the code is a lot I'm posting what I think is relevant to this question. There is no particular reason to have two methods since all the logic can be implemented in just one. The separation was part of my attempts to add the delay I want.
Currently the logic itself is plain simple - cells
is an array of objects, and each object provides a way to select a unique DOM elemten by using this:
document.querySelector('[data-cellNumber="' + id + '"]');
I'm not sure that it's becoming clear from the code I've pasted but the simple idea is that every time I select a cell and ultimately change it's background color I want to add some sort of delay so you can see the sequence in which the cells are painted.