Reputation: 353
I have an array, a simplified form would be this:
let array = [
{id: 1, value: 0},
{id: 2, value: 0},
{id: 3, value: 0}
];
Now I want to create an interval, that increments the value on the object with id: 3 every second.
What I would do now is target the object with
array[2].value
. This works as long as the array doesn't change.
The array I use is changing constantly, that means that elements get deleted/add in an asynchronous manner. When that happens the interval is pointing at the wrong element. If I would delete element [1] in the example, the interval would now point at an undefined element ([2]).
I was thinking of using an associative array (id as index), but in Angular ngFor does not work reliably anymore when I do that. Objects are also not working because of the same reason.
How can I create an interval that changes a property of an array element even when the index changes? Or is there a better solution to my problem?
Upvotes: 0
Views: 1822
Reputation: 18281
You should hold a reference to the object, instead of using the index each time. For Example:
let array = [
{id: 1, value: 0},
{id: 2, value: 0},
{id: 3, value: 0}
];
function startIncrementing(elem) {
setInterval(() => elem.value += 5, 500);
}
// Log the array every second
setInterval(() => console.log(array), 1000);
// Start the increment interval
startIncrementing(array[2]);
// Remove an elemnt after 1 second
setTimeout(() => array.splice(1, 1), 1000);
Upvotes: 1
Reputation: 1452
Use find
method:
function updateValue () {
var item = array.find(item => item.id === 3)
if (item) item.value++
}
setTimeout(updateValue, 1000)
Upvotes: 1