I found this codesnipe in a famous tool by greensock (SplitText)
Why is the for-loop only running once? In my opinion it must run three times (tt.length). Any explanation is welcome.
var u = "undefined" != typeof window,
tt = ["AAA", "BB", "CCC"],
F = tt.length;
for (setTimeout(function checkWarn() {
if (u)
console.log("is u", F)
else {
console.log("is not u")
}
}, 50); - 1 < --F;);
2
Answers
The
setTimeout
is part of the initialization of thefor
loop declaration. This particular block is only run once.Furthermore,
for(…);
is a "empty statement" loop which would rely entirely on side-effects in thecondition
andafterthought
expressions.The following is likely closer to what you need, albeit not exactly my cup of tea:
The
setTimeout(...)
is (very oddly) placed inside the loop initializer part, where one would normally put more useful code likelet i = 0;
. The initializer part runs only once by definition.The
setTimeout
then causes the function inside it to be excuted also exactly once, after a short delay. By that time thefor
loop has already finished running because it has decrementedF
until it became-1
so that value is what the inner function then prints.