Function within function

Asked

Viewed 365 times

1

These days, I asked a question here at Sopt and the boy answered me with a code, creating a function within another function, something simple, but I didn’t use it, and I started to implement.

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 to 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 between parentheses. Why?

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

1 answer

1

The parentheses around the function is because this is a self-executable function. Note that just after the parentheses around it, 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 will 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 website of Braziljs has an article explaining better, if interested: https://braziljs.org/blog/funcoes-em-javascript/

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.