Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Javascript synchronous when manipulating the DOM?

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?

like image 833
Cesar Avatar asked Jul 22 '16 09:07

Cesar


People also ask

Is DOM manipulation asynchronous?

DOM manipulation is synchronous, however, the browser's re-rendering of the page in response to a DOM update is asynchronous. This can give the illusion of an asynchronous DOM update.

Is the Dom synchronous?

Event execution can be both synchronous and asynchronous in terms of IPC tunneling, and it is always synchronous in terms of DOM.

How does DOM manipulation work JavaScript?

DOM manipulation is the interaction of the JavaScript DOM API to modify or change the HTML document. With DOM manipulation, you can create, modify, style, or delete elements without a refresh. It also promotes user interactivity with browsers. You can use different programming languages to manipulate the DOM.

Are DOM events synchronous?

log() yields this result isn't surprising because a DOM update is a synchronous event.


1 Answers

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

like image 154
T.J. Crowder Avatar answered Oct 18 '22 20:10

T.J. Crowder