I have a form with an input of type field. I have several radiobuttons, and depending on which of them I click, the value in the input type field will be updated. After that, I will call a Javascript function to perform certain action, and the function will use the updated quantity (text) in the input field.
Of course, it is more secure to pass that quantity to the function itself, but could I rely on Javascript first updating the DOM, displaying the update input field value, and with that, retrieving it viadocument.getElementById("input-quantity").value
and using this in the function? Or could the function get the "old" value if the refresh of the DOM takes its time?
As you said, just passing the value to the function would be preferred.
But yes, setting the value of an input is synchronous; in what you describe, you will reliably get the updated value, cross-browser. Other DOM manipulations (inserting elements, removing them, moving them) are also synchronous, although the user may not see the result until your JavaScript code completes, letting the browser use the thread to repaint the display. (Although JavaScript is not inherently single-threaded, browsers use a single main UI thread to run your JavaScript code, and typically also use that thread to update the display.)
来源:https://stackoverflow.com/questions/38522561/is-javascript-synchronous-when-manipulating-the-dom