Chris Bornhoft
Chris Bornhoft

Reputation: 4291

Removing items from array and DOM simultaneously

I have a large array of items which I am removing one by one within a setInterval.

var randomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

var showItems = function() {
    $.each(items, function(key, val) {
        $('.list').append('<div class="item" id="i'+key+'">'+val+'</div>');
    });
};

var interval = setInterval(function() {
    var id = randomInt(0, items.length);
    items.splice(id, 1);
    $('#i'+id).remove();
    if (items.length < 10) {clearInterval(interval);}
}, 200);

The problem arises when the list starts to become shorter. Let's say items starts with 500 entries. Once items.length equals 200, the ids within the DOM stay the same. This results in items being deleted from the array while not from the DOM.

Another method I've thought of is delete items[id], but then there's the problem of sparse removal when an item has already been deleted. Once the defined item count reaches ~20, it takes an exceptionally long time for anything more to happen.

The solution I can think of is to redraw the DOM at every delete but that sounds awful and the results (both aesthetic and computational) would be ugly!

Upvotes: 0

Views: 116

Answers (1)

Sanjo
Sanjo

Reputation: 1250

Instead of using IDs for your DIVs, do something like this:

<div class="list">
  <div class="item">First DIV</div>
  <div class="item">Second DIV</div>
  ...
</div>

Instead of $('#i'+id).remove(); do $('.list > .item').eq(id).remove();

Upvotes: 2

Related Questions