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>
>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.