skip to Main Content

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


  1. The setTimeout is part of the initialization of the for loop declaration. This particular block is only run once.

    Furthermore, for(…); is a "empty statement" loop which would rely entirely on side-effects in the condition and afterthought expressions.

    The following is likely closer to what you need, albeit not exactly my cup of tea:

    for (; -1 < --F;) {
      setTimeout(function checkWarn() {
        if (u)
          console.log("is u", F)
        else {
          console.log("is not u")
        }
      }, 50);
    }
    
    Login or Signup to reply.
  2. The setTimeout(...) is (very oddly) placed inside the loop initializer part, where one would normally put more useful code like let 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 the for loop has already finished running because it has decremented F until it became -1 so that value is what the inner function then prints.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search