Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

About execution order of onclick in JavaScript

I have a question about the execution order of the onclick attribute in JavaScript.

I would like to know why the function written after form submission is executed.
Why is it not run from above?

<form action="post" name="formTest">
    <button type="button" onclick="A(B)" id="test">test</button>
</form>
<script>
    function A(B) {
        formTest.submit();
        B();
    }

    function B() {
            window.alert('Function B');
    }
</script>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Form submissions, and formTest.submit(), are asynchronous, meaning they are executed but the browser doesn’t wait for them to finish before moving on to the next line of code.

Because submitting a form is a relatively long process compared to firing an alert (ie: you have to make a HTTP request and receive a response from the server) the browser runs formTest.submit(), runs alert(), then the submission completes from the background.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading