[Vuejs]-VueJS doesn't re-render until loop is finished

2👍

No, this is how Javascript eventloop works in browsers (and not only).

You can imagine that Javascript only gets executed in “gaps between moments”, so that your picture of what happens in the browser is a still snapshot of the moment.

1👍

Wrapping up and as a merge of all the suggestions, I have understood that:

  • In the middle of a JS loop VueJS is not gonna re-render anything

So you have to move the iterations of your loop to another process. I was thinking that promises can be a solution but an easier one is to use setTimeout() without the delay param.

So instead of this:

for(var i = 0; i < 10000; i++ ) { 
  this.blink() 
};

My code would look like this:

for(var i = 0; i < 10000; i++ ) { 
  setTimeout(this.blink)
}

0👍

You could write something loop-like that uses setTimeout to let changes be noticed by Vue and then pushed to the DOM.

beforeDestroy() {
  if (this.timeout != null) {
    clearTimeout(this.timeout);
    this.timeout = null;
  }
},
startWithLoop: function() {
  console.log("startWithLoop");
  let i = 0
  const iter = () => {
    this.blink();
    i += 1;
    if (i < 10000) {
      this.timeout = setTimeout(iter);
    }
  }
  iter();
},

Working fiddle with the changes from above: https://jsfiddle.net/ssorallen/9pqscat1/3/

Leave a comment