Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

Lets say that my program is currently in a for loop, but for some reason its taking too long. Lets say that somehow the algorithm is so slow that it takes about 500ms to loop through maybe 100 elements in the array.

Is it possible that while the program is inside the array, perhaps doing work with element number 50, that I get incoming commands from the network, telling me to add more elements or delete elements from the array?

A practical example is a matchmaking queue server. Every time a user joins, the server will try to match players as best as it can by calling a function, but it may be possible that a player who is in the queue, who hasn't been "reached" yet by the function, to simply leave and exit. Would this somehow corrupt the for loop search?

Summary: I have an array I want to loop through, can it have its elements changed (add/delete) during the for loop caused by external functions? Or will those functions be called after the program is done with the for loop? (Like a database being locked while a query is being worked into it to prevent these same problems)

share|improve this question
up vote 3 down vote accepted

JavaScript runs on a single event loop. So long as it is running your function, it won't run any other function.

If you get an event saying that an item should be added to the array, then the event handler for that event can't fire until the currently running function is finished.

share|improve this answer
    
unless you are using shared memory concept between different forks/cores blog.varunajayasiri.com/shared-memory-with-nodejs – gurvinder372 Jul 8 at 9:14
    
What if the other function is in a callback? – Don Warren Jul 8 at 9:40
    
@DonWarren — Then the function that calls it couldn't run while the other function was running. – Quentin Jul 8 at 9:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.