Skip to content Skip to sidebar Skip to footer

Is It Possible For A Concurrent Read/write Read/write Collision In Javascript In The Browser?

I have a situation where I am making several (say four) ajax calls (using AngularJS http get, if that matters) and I want each call to callback and increment a counter, so I can kn

Solution 1:

No, it is not possible (no collision will occur). Each AJAX call response can be considered a message on the JavaScript message queue. The JavaScript runtime processes each message on the queue to completion before processing the next. In other words, it calls the callback for the event and runs the full callback function (and all the functions it calls, and so on) to completion before moving onto the next message in the queue. Therefore, no two messages (e.g., AJAX responses) will be processed in parallel.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop

Also, I've worked in JavaScript for many years and can guarantee this is how it works.

Solution 2:

like you mentioned, since javascript is single threaded, I do not think such a scenraio would happen, the only way js becomes multi threaded is when you use webworkers, but even they do not share the same variables( they clone the attribute js objects you pass, i am assuming here), so there should be any case of read/write overlap

EDIT

on second thought, say there is function onCounterIncreament which would do a bunch of operation when counter increments, if you do not call it immediately after you increamenting counter, but use $watch or something timeout fn to check for change in counter, there is a good possiblity you might miss a change.

Post a Comment for "Is It Possible For A Concurrent Read/write Read/write Collision In Javascript In The Browser?"