I want to progressively change the color of the cells of a table, but always leave the setTimeout for the end, as it could prevent the whole loop from being executed at the same time.
document.querySelector("#borrar").addEventListener("click", function () {
if (document.querySelector("#del") != null) {
for (let td of document.querySelectorAll("#del tr td")) {
setTimeout(function () {
td.style["background-color"] = "white"
}, 3000);
}
}
});
The function
setTimeout
makes more sense when you think of it as "Run this function when at least x milliseconds have elapsed from now ".Your code waits 3 seconds and runs the first one, checks if it should run the next one, "- 3 seconds passed? - yes" then run it, and so on. The condition to execute is fulfilled in all.
What you can do is vary the execution time, the first expects 1, the second 2 and so on. An example: