Handling multiple collection.add events in a batch

I had this problem in a web app where I would fetch a list of new models for a collection & those model would inevitably trigger the add event that would add them separately on the page.

However as you guys know it’s always better to add 1 element containing all your new views than adding each one separately.

In the end I decided to settle for throttling the add event with a little setTimeout() collecting all the model to be rendered for 30ms, bundling together those views in a fragment & then pushing that in the DOM.

The solution is really simple, in my render method I just added:

this.modelsToAdd.push(model);
if(this.batchAdd) clearTimeout(this.batchAdd)
this.batchAdd = setTimeout(function(){
    // render the list with the batched models
    self.renderList(self.modelsToAdd);
    self.modelsToAdd= [];
},30);

So I effectively slowing down the rendering of my view list by 30ms but for me it’s really worth it in performance.

Cedric Dugas is a front-end veteran with more than 9 years under the belt, between his open source projects & entrepreneurial ambitions he is a product architect at CakeMail. Why don't you follow him on twitter.

One Comment on "Handling multiple collection.add events in a batch"

  1. Avi Block says:

    By the way, this is called “debounce” not “throttle”, and you should be able to use underscore for that.

Got something to say? Go for it!