In the code snippet below, I have a setInterval followed by my console.log. As you can see, endNode is initialized to null which should be updated inside setInterval and the console.log should print the updated node. At least, that is what I am trying to achieve.
However, in my console, I get null as the output. It seems like playing with some more code that the lines (console.log in this case) are executed before setInterval is executed. Or perhaps it may be a scoping issue.
Is there a way to fix this so that I am able to print the updated value of endNode?
let endNode = null;
let BFStimer = setInterval(function() {
if (Q.size() > 0) {
let u = Q.dequeue();
if (u.end) {
$(".r" + u.x + "c" + u.y).addClass("explored");
setTimeout(function() {
clearInterval(BFStimer);
});
endNode = u;
return u;
}
let N = u.neighbor;
for (let i = 0; i < N.length; i++) {
if (N[i].isWall) {
continue;
}
if (N[i].status === "undiscovered") {
N[i].status = "discovered";
$(".r" + N[i].x + "c" + N[i].y).addClass("discovered");
N[i].parent = u;
N[i].distance = u.distance + 1;
Q.enqueue(N[i]);
}
}
$(".r" + u.x + "c" + u.y).addClass("explored");
}
}, 5);
let currentPathNode = endNode;
console.log(currentPathNode);
This is the intended behavior, it's not a bug and thus there's no fix. When you call setInterval, setTimeout, nextTick, and so on you are not immediately executing the code, but you are scheduling a task that will be executed when the current micro/macro task is finished.
You can just move the code to an external function and call it both inside and outside the setInterval:
function myFunc() {
if (Q.size() > 0) {
let u = Q.dequeue();
if (u.end) {
$(".r" + u.x + "c" + u.y).addClass("explored");
setTimeout(function() {
clearInterval(BFStimer);
});
endNode = u;
return u;
}
let N = u.neighbor;
for (let i = 0; i < N.length; i++) {
if (N[i].isWall) {
continue;
}
if (N[i].status === "undiscovered") {
N[i].status = "discovered";
$(".r" + N[i].x + "c" + N[i].y).addClass("discovered");
N[i].parent = u;
N[i].distance = u.distance + 1;
Q.enqueue(N[i]);
}
}
$(".r" + u.x + "c" + u.y).addClass("explored");
}
}
myFunc();
let BFStimer = setInterval(function() {
myFunc();
}, 5);