Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wait/pause in between underscore/backbone .each iteration?

Inside my Backbone view, I want to iterate over a collection, and render a new child view for each item, but with a small delay in between (about 200ms). In the example, Flock is a collection of Backbone models called Sheep :)

render: function () {
  Flock.each(this.renderSheep)
},

renderSheep: function (mySheepModel) {
   var sheep = new SheepView({model:mySheepModel})
   $(sheep.render().el).appendTo('#field').fadeIn();
}

How would I go about this?

like image 274
user888734 Avatar asked Sep 20 '26 04:09

user888734


1 Answers

This should work:

render: function () {
    var i = 0,
        _self = this;

    (function renderSheepWithDelay(delay) {
        if (i <= Flock.length) {
        _self.renderSheep(Flock.at(i));
            i += 1;
        setTimeout(renderSheepWithDelay, delay);
        }
    })(200);
},

Basically, you're using a recursive function to call itself after a given delay which you pass in. The function is iterating through the models in the collection and will stop recursively calling itself when it's exhausted the collection.

like image 163
robmisio Avatar answered Sep 21 '26 18:09

robmisio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!