0

I have a IIFE

(function test() {
  console.log("test called!");
})();

Does some way exist that I can call test later on?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
seventeen
  • 557
  • 1
  • 6
  • 21
  • 1
    No, because I simply mean how can I use an iify and treat the function as a normal function at the same time. – seventeen Apr 22 '21 at 21:35
  • 4
    I'm not following you. An IIFE (not IIFY) is an immediately invoking function expression. If you're not invoking it immediately it is by definition not an IIFE anymore. If you want to execute that function after some time, then pass it to `setTimeout()`. What actual problem are you trying to solve here? – Ivar Apr 22 '21 at 21:37
  • 4
    Just make it a function and call it right after and the later in your code? – Dominik Apr 22 '21 at 21:38
  • I was just curious as to why I cant access test later on. Its not a problem I have. – seventeen Apr 22 '21 at 21:48
  • 4
    @seventeen Because by adding parenthesis around the function, it is no longer a function declaration, but a function expression (a [_named_ function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#named_function_expression) to be precise). And the name of the function is only scoped to the body of the function itself, not outside of it. See [Javascript functions like “var foo = function bar() …”?](https://stackoverflow.com/questions/16631708/javascript-functions-like-var-foo-function-bar) – Ivar Apr 22 '21 at 21:55
  • 1
    If you really want to have this, you can do [this](https://jsfiddle.net/knqv2gbu/1/) – yaakov Apr 22 '21 at 21:57
  • @ivar that makes sense. Thanks. – seventeen Apr 22 '21 at 22:16
  • @YaakovAinspan Thanks, I now see how it could work. – seventeen Apr 22 '21 at 22:17
  • It's called IIF**E** - because is short for **I**mmediately **I**nvoked **F**unction **E**xpression. – VLAZ Apr 23 '21 at 04:45
  • Does this answer your question? [Execute script after specific delay using JavaScript](https://stackoverflow.com/questions/24849/execute-script-after-specific-delay-using-javascript) – yudhiesh Apr 23 '21 at 04:48

1 Answers1

1

IIFE gets invoked immediately and returns the result. You can't call it later.

If you want to call it later, create a normal function.

However if you really want to do this, there's a workaround. Create a global variable and assign the function to it. BUT I recommend creating a regular function for this purpose.

(function test() {
  window.testFn = test;
  console.log("test called!");
})();

testFn();
Sagar V
  • 12,158
  • 7
  • 41
  • 68