Because setTimeout() is asynchronous and non-blocking, your for loop just sets a bunch of timers and then immediately runs the code that checks the total before any of the timers have fired and thus before any of the timers have incremented the total value.
To fix, you can change the timeout to be a promise and use async and await to run the loop sequentially:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function run() {
const arr = [1, 2, 1, 2, 1, 2, 1];
let total = 0;
for (let a of arr) {
await delay(1000);
if (a === 1) {
total++;
}
}
if (total === 4) {
console.log('true');
} else {
console.log('false');
}
}
run();
Or, to run all the timers in parallel:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function run() {
const arr = [1, 2, 1, 2, 1, 2, 1];
let total = 0;
await Promise.all(arr.map(a => {
return delay(1000).then(() => {
if (a === 1) total++;
});
}));
if (total === 4) {
console.log('true');
} else {
console.log('false');
}
}
run();