In my multiuser live nods.js app, I have a function that removes a specific element from an array. It's an asyn function and can potentially be called by two different users independently and probably at the same time (client-site socket trigger) to perform the operation on the same array.
myUsers= [];
myUsers.push('user1');
myUsers.push('user2');
myUsers.push('user3');
function removeUser(user){
for(var i=0; i<=myUsers.length; i++){
if(user===myUsers[i]){
myUsers.splice(i,1);
break;
} } }
Should I be worried that it might lead to removing the wrong/unintended element as a result of both operations happening simultaneously? Like, when removeUser('user1')
and removeUser('user3')
are both called at the same time (client-site socket trigger), and while user1
is being spliced, and user3
has reached at i=2
it might remove user2
instead of user3
? And i
might even now go over the loop's original limit (myUsers.length)?
Is my concern valid? If so, what would be the solution?