0

I can't wrap my head around this parenthesis statement and the purpose it serves, can anyone help me out?

function fadeOut(el){
      el.style.opacity = 1;

      (function fade() {  <-- If this is true, then it keeps on executing?
        if ((el.style.opacity -= .1) < 0) {
          el.style.display = "none";
        } else {
          requestAnimationFrame(fade);
        }
      })();
    };
Lukas
  • 151
  • 1
  • 8

1 Answers1

0

To me, this looks like the function fade is used recursively. In the line requestAnimationFrame(fade);, it actually transmits a reference to itself as a parameter. Therefore, this method makes sure, that it executes itself at least once, but in the case where the inner if statement is false, it will call the function requestAnimationFrame with itself as the parameter. So maybe this requestAnimationFrame will call fade() again.

By the way, I disagree with @VLAZ and @Rajesh. I don't see, that the linked question properly answers the usage of this construct in the context of your example. This function is neither uses for variable scoping, nor for overwriting framework properties.

André Reichelt
  • 1,484
  • 18
  • 52
  • It's an IIFE. (Some) of the answers in the dupe explain what an IIFE is. Sure, others focus more on the particular scoping problem being solved with an IIFE but still - the general concept is that it's an immediately invoked function expression. – VLAZ Sep 13 '19 at 09:05
  • @VLAZ I see your point. And thanks for the abbreviation, that I've never heard before. I still think, that this question is a special case of an IIFE, where it's also used for some kind of a recursion. That's why I added my answer. Just to make clear, that in this specific example, it fulfills some extra purpose. – André Reichelt Sep 13 '19 at 09:10