Reputation: 343
There is a javascript code that has variable messageList
keeping the messages list and this can be updated by a function updateMessageList()
as below:
var messageList=[]; //contains list of messages
function updateMessageList(id, lastUpdate); //updates messageList item for given id
//at some point while running
mesasgeList=[
{id:1, lastUpdate:1371650818000},
{id:2, lastUpdate:1371650821000},
.....
]
What happens if two different sources call updateMessageList()
function at he same time for same messageList
item. Let's say one update for message with id:1
comes from client (current user updating the message) and another from the server also for message with id:1
(another user updates the message). They will both then try to access and modify messageList[0].lastUpdate
property at the same time.
In Source 1: When the client updates the message form submit event triggers the function handleReply()
function handleReply(event) {
.....
var id=event.currentTarget.find('input[name="id"]').val();
//form has an hidden input for id of the message
var d = new Date();
updateMessageList(id, d.getTime());
.....
}
In Source 2: JS makes a AJAX call to server to check if there are any updates, and than runsupdateMessages()
function in return
//server sends following JSON data:{id:1, lastUpdate:1371650823269}
function updateMessages(data) {
.....
updateMessageList(data.id, data.lastUpdate);
.....
}
The updateMessageList()
functions will both try to change lastUpdate
property of messageList[0]
.
So should we think these kind of situations while programming or does javascript can handle these?
Upvotes: 2
Views: 798
Reputation: 27247
Javascript is single-threaded. There is no such thing as concurrency in javascript. One call will always be before or after the other. Maybe it can differ by a millisecond, but one call will exit its block before the other begins.
Upvotes: 8