Building a Sort-Visualizer in React using the Create-React-App [https://roy-05.github.io/sort-visualizer/ ]
I\'m animating each iteration of the loop using setTimeou
I also encountered same warning. In my case, I declared variable outside the iteration, but modified variable inside forEach
method.
Something like:
// some code above
let validInputs = true;
someInputs.forEach( input => {
validInputs = input.value && validInputs;
})
After I did some reserch, I found in this post, JSHint error : Functions declared within loops referencing an outer scoped variable may lead to confusing semantics, mentioned that JSHint doesn't like how the anonymous function in there is being re-created over and over.
I changed forEach
arrow function to for (let index i = 0; index < someInputs.length; index++)
, and the warning is gone.
Perhaps in your case, change setTimeout
to traditional non-arrow function can remove the warning.
You're correct that modifying the variable inside setTimeout
is causing the issue. You can get around this by wrapping setTimeout
inside a promise and waiting for it to resolve before modifying your variables. This is much cleaner using async/await
:
for (let i = 0; i < arr.length - 1; i++) {
let minimum = i;
await new Promise(resolve => setTimeout(resolve, i * 400));
for (let j = i + 1; j < arr.length; j++) {
array_bar[j].style.backgroundColor = "red";
array_bar[minimum].style.backgroundColor = "blue";
await new Promise(resolve => setTimeout(resolve, (j - 1) * 400));
if (arr[j] < arr[minimum]) {
array_bar[minimum].style.backgroundColor = "lightblue";
minimum = j;
}
}
}
With each loop, you're creating a promise that resolves once the timeout is expired. Using await
will pause execution of your function until the promise resolves. Then, you can modify variables like minimum
because they are no longer within the scope of the callback function you were originally passing into setTimeout
.