1

What are the best practices for adding an object to a javascript array while it is currently in use in an interval method?

function someEvent()
{
    array.push("something");
}

function update()
{
    array.forEach(function(o, i, a))
    {
       // do something with the object and delete it 
    });
}

var updateInterval = setInterval(update, 1000);

This is used in Angular context. I know there are some things in Javascript like calling a function will never call that function before the other function has finished, what applies to interval and the use of arrays like this?

Deukalion
  • 2,296
  • 8
  • 30
  • 48
  • Do you feel as if I answered your question completely? If so, please don’t forget to mark my answer as "accepted" by using the checkmark. If your question hasn't been fully answered, please elaborate on what else you need to know so the community can provide you with further help! Thanks! – Maximillian Laumeister Aug 06 '15 at 02:44

1 Answers1

2

Modifying data that setInterval is using won't cause any problems, for the reasons you specified. Because of JavaScript's single-threaded nature. Setinterval creates the illusion of concurrency, but if other code is running it goes into a queue, so there won't be any threading errors.

So even if we don't know whether for instance a click handler or a setInterval handler will be called first, we can guarantee that they will not be called concurrently.

See more details in this answer.

Community
  • 1
  • 1
Maximillian Laumeister
  • 19,107
  • 7
  • 56
  • 76