VueJS waits until the loop is complete before executing a re-render

Check out this VueJS code snippet:

new Vue({
  el: '#app',
  data: {
    tiles: [
      { isActive: false },
      { isActive: false },
      { isActive: false },
      { isActive: false },
      { isActive: false }
    ]

  },
  methods: {
    startWithLoop: function() {
      console.log("startWithLoop");
      for(var i = 0; i < 10000; i++ ) { this.blink() };
    },
    startWithInterval: function() {
      console.log("startWithInteral");
      setInterval(this.blink);
    },
    blink: function(){
      console.log("blink");
      var index = Math.floor(Math.random() * this.tiles.length);
      this.tiles[index].isActive = !this.tiles[index].isActive;
    }
  }
})

By calling the startWithInterval method, you can witness constant changes in the view as the state of tiles fluctuates.

However, if you use the startWithLoop method, there won't be visible changes in the view until the loop completes its iterations.

You can access the JSFiddle example here.

Is there a way to trigger immediate view updates during each step of the loop?

Answer №1

This is the inner workings of the Javascript event loop in web browsers, and beyond.

Think of Javascript running only during pauses in time, creating a freeze-frame effect of what occurs in the browser at any given moment.

Answer №2

Concluding and synthesizing all the suggestions, I have come to understand that:

  • In the midst of a JS loop, VueJS will not trigger a re-rendering

Therefore, it is necessary to move the iterations of your loop to a separate process. While I initially considered using promises as a potential solution, a simpler alternative is to utilize setTimeout() without specifying the delay.

So instead of the original code snippet:

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

The revised code would be structured like this:

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

Answer №3

To achieve the desired effect, you can create a loop-like structure using setTimeout to ensure that changes are detected by Vue and then applied 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();
},

To see these modifications in action, check out this working fiddle: https://jsfiddle.net/ssorallen/9pqscat1/3/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with Laravel routes and jQuery $.post()? Keep getting a frustrating 404 Not Found error?

A JavaScript file with jQuery that is responsible for sending a POST request $.post('log_in', { email: email, password: password }, function(response) { $('#log_in_result').html(response); console.log(response); }); In the Lar ...

What is the most straightforward method to convert a current Express node app into a static site?

After primarily working with React and create-react-app, I've grown accustomed to the convenience of having a build utility for npm that simplifies deploying projects to static web hosting platforms like github pages or surge. This process ultimately ...

Updating the Laravel array using Vue components can be done by accessing the array

I'm currently working with a Vue template and attempting to retrieve the pets array. https://i.sstatic.net/pgxWJ.png This is the snippet of code that I am using: foreach ($request->pets as $pet) { $pet = $client->pets()->find($pet)-> ...

Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array. Below is the service where I am retrieving data from Firebase: File name: subcategory.service.ts export class SubcategoryService { subcategoryRef: Angula ...

Convert the text inside a span element into a key-value object in JavaScript

How can I extract and save the text from a span element as key value pairs within a div? <div class="data-diff-span__composite-list-item__18c5zip data-diff-core__highlight-area__19c0zip"> <div class="data-diff-basic__class-row__4n ...

Extracting Vertices, Edges, Faces, and Triangles from GLB Model Using ThreeJS GLTFLoader

I am looking to incorporate basic information about the model into my model viewer. Specifically, I need to obtain the vertex, edge, face, and triangle count of the object, or at the very least, the vertex count. My attempted approach involves using the f ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

JavaScript code that deletes text from a document - Script eradication

I am trying to display the message "Todays Beer Style is: "Beer Style". However, when I add the javascript code, the "Todays Beer Style is:" text disappears. I'm not sure why this is happening. Below is the HTML code for reference. HTML Code <!DO ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

Using jQuery to select all child elements based on a specified condition

Is there a way to locate all instances of .post-comment-replies that have a nested '.post-comment-reply' within them, rather than being at the first level? Currently, the code provided retrieves not only those .post-comment-replies with nested . ...

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

Struggling with running my React App as I'm encountering some errors

Check out the code on Github: https://github.com/bhatvikrant/IndecisionApp I have already run npm i and then executed yarn run dev-server, utilizing webpack. My operating system is MacOs. I have also created the .babelrc file. The issue I encountered aft ...

Discovering Geo Coordinates with Vue.js

To ensure accuracy, I am setting a 10,000 millisecond timeout to retrieve the client's current geolocation. var options = { timeout: 10000 }; This function is written in JavaScript: function getCoordinates() { return new Promise(functi ...

Sending arguments from JavaScript to PHP via ajax

I am facing a challenge where I need to send a JavaScript variable to a PHP function. While I was successful in doing this with hard-coded values, I'm struggling when it comes to using variables. Here's an example of what worked for me: <butt ...

Experiment with jQuery and JavaScript compatibility specifically on Internet Explorer 6

Seeking advice on the most effective method to test my web app using IE6. I currently have IE8 installed on my computer, and am considering utilizing a Virtual Machine. Are there any other alternatives worth exploring? It is imperative that my jQuery and ...

What is causing the array elements to be iterated through multiple times?

My goal is to display all the titles from an array called 'title element' containing 10 values. However, I am encountering a problem: The for loop outputs all 10 values repeatedly 10 times. The titles are: Title 1, Title 2, Title 3, Title 4, T ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

Ways to transform an Array into an object

I had the idea to create a personalized dictionary for customers by utilizing the reduce function. Currently, I am achieving this using the forEach method. const customers = [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: ' ...