Reputation: 2655
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?
Upvotes: 1
Views: 39
Reputation: 20359
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.
Upvotes: 2