Function within function [duplicate]

1

These days, I asked a question here in SOpt and the guy answered me with a code, creating a function within another function , something simple, but I did not use it, and I started to implement it.

function QuantosEmEstoqueAbrir(){
    $j('.availability-only').attr("style", "transform: translate(0);");
    function QuantosEmEstoqueFechar(){
        $j('.availability-only').attr("style", "transform: translate(300px);");
    } setTimeout(QuantosEmEstoqueFechar, 10000);
}
setTimeout(QuantosEmEstoqueAbrir, 10000);

This is a "mini notification" I made for a store system, and it's working fine!

But my question is this, looking at the code mentioned above, which the boy gave me in response:

function domReady(cb) {
  (function checkDomReady() {
    var state = document.readyState;
    if (state == 'loaded' || state == 'complete') cb();
    else setTimeout(checkDomReady, 200);
  })();
};

He used his function in parentheses. Why this?

 (function checkDomReady() {
    var state = document.readyState;
    if (state == 'loaded' || state == 'complete') cb();
    else setTimeout(checkDomReady, 200);
  })
    
asked by anonymous 11.10.2017 / 19:52

1 answer

1

The parentheses around the function is why this is an auto-executable function. Note that soon after the parentheses around, it is running ()

(function checkDomReady() {
var state = document.readyState;
if (state == 'loaded' || state == 'complete') cb();
else setTimeout(checkDomReady, 200);
})();

If you run without the parentheses around, you get a syntax error:

function checkDomReady() {
var state = document.readyState;
if (state == 'loaded' || state == 'complete') cb();
else setTimeout(checkDomReady, 200);
}();

Uncaught SyntaxError: Unexpected token )

On the BrazilJS website you have an article explaining better, if you are interested: link

I hope I have helped.

    
11.10.2017 / 20:09