V
V
vinilzen2013-11-19 22:53:48
JavaScript
vinilzen, 2013-11-19 22:53:48

What is the problem with the sequence of events in js?

Good time of day,
I will be grateful for advice, or at least kick in which direction to look.
There is a long-playing element rendering on Backbone, the code is below
or here is an example with a problem on jsbin

var MyView = Backbone.View.extend({
  tagName:'p',
  className:'List',
  page:1,
  render: function(widget_collection) {
    while ( this.page < 15 ) {
      this.createPage();
      this.addToLogNumberPage(this.page);
      this.page++;
    }
    return this;
  },
  addToLogNumberPage:function(page){
    console.log('add:'+page);
    $('.log').append('Page N'+page+'printed, ');
  },
  createPage:function(){
    var i = 0;
    while (i<100000000){ i++; }
    this.$el.append('<span>'+this.page+'</span>')
  }
})

var my_view = new MyView();

$('button').click(function(){
  $('.progressBar').show();
  $('.log').show();
  $('body').append(my_view.render().el);
})

Can't figure out why .progressBar and .log is showing up after all elements are rendered even though console.log('add:'+page); prints as it goes...
DOM seems to hang, rendering everything only after render() is done

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2013-11-20
@vinilzen

You have witnessed one of the optimizations of modern browsers.
http://jsbin.com/OBaMoqe/1 - I marked the main point in the comments, but I repeat
when you need to do something bold, you must certainly take this matter out of the general execution context (via setTimeout or preferably webworkers), otherwise the rest of the code and all redraw events will wait for this fat logic to finish.
js is an asynchronous language. The whole point of the language is that all heavy calculations can and should be carried out in parallel.

M
Mikhail Osher, 2013-11-19
@miraage

I'm not sure, but maybe the DOM manipulation will actually be done when the entire click() function completes. If so, then the behavior is very strange.

V
Vitaly Zheltyakov, 2013-11-20
@VitaZheltyakov

How long does it take to process the show() method by default?
Most likely, your progressBar does not have time to appear - its animation is blocked by calculations. The DOM is not updated until the calculations are over.
This is solved simply: either we show the progressBar immediately without animation, or we delay the calculations for the duration of the animation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question