Updating state in Vue by utilizing an array of item values

Hello everyone

In a simple application, I am attempting to visualize the insertion sort algorithm using Vue. I have successfully written a function that sorts a list of items and returns an array showing each step of the sorting process. The final array in this array represents the fully sorted version of the original array. My goal is to update the state and replace the original unsorted array with each value from the array of steps returned by the function;

Below is my insertion sort function:

const insertionSort = (unsortedItems) => {
let sortedList = [...unsortedItems];
let sortingProcess = [];
for (let i = 1; i < sortedList.length; i++) {
   let current = sortedList[i];
   let j = i - 1;
   while (j >= 0 && sortedList[j] > current) {
      sortedList[j + 1] = sortedList[j];
      j--;
      sortingProcess.push(sortedList);
    }
    sortedList[j + 1] = current;
    sortingProcess.push(sortedList);
   }
   return sortingProcess;
 };

 export default insertionSort;

Here is where I attempt to update my state:

insertionSort(this.unsortedList).forEach(round =>
    setTimeout(() => (this.unsortedList = round), 600)
  );

I expected the above code to update my state every 600 ms. However, when clicking the sort button, the array instantly sorts and I do not get to see each step of the sorting process. What could be wrong with my code?

Answer №1

This question is not specific to Vue, but rather related to a common JavaScript interview question. The issue lies in using forEach() to loop over an array and set a timeout on each item without closure scope. This results in all items being executed simultaneously 600ms from now. One possible solution is as follows:

insertionSort(this.unsortedList).forEach((round, i) =>
    setTimeout(() => (this.unsortedList = round), i * 600)
  );

For more information, click here

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

Tips and tricks for activating javax.script in Websphere liberty profile on Bluemix

I am looking to incorporate JavaScript into one of my Java applications. In order to test this, I executed the following code: javax.script.ScriptEngineManager manager = new ScriptEngineManager(); javax.script.ScriptEngine engine = manager.getEngineByName ...

Issue encountered while trying to load electron-tabs module and unable to generate tabs within electron framework

I've recently set up the electron-modules package in order to incorporate tabs within my Electron project. Below are snippets from the package.json, main.js, and index.html files. package.json { "name": "Backoffice", "version": "1.0.0", "descr ...

Creating a never-ending scroll feature on a static page in Next.js

I am in the process of creating a portfolio using Next.js and have a large number of projects on the page. I would like to implement a feature where images start loading only when they enter the current viewport. This functionality works well with the defa ...

The Model Viewer module is unable to load the three-dimensional model

Attempting to incorporate a 3D model into my website using the modelviewer library, but encountering difficulties in loading the file as shown below: Just to note, I am utilizing github pages with a custom domain from godaddy which may be contributing to ...

Debugging JavaScript in ASP .NET (solving quick breakpoint problems)

There seems to be a mystery about setting breakpoints in my JavaScript code - sometimes it works, other times it doesn't. Despite all efforts, I can't seem to figure out what factors contribute to this inconsistency. While debugging the dynamic p ...

Ways to ensure that the height of the second row in the second column matches that of the first column

My current layout design is causing an issue where the lower green box extends beyond the total height of the entire box. I've provided a rough version of my code on codepen. Using the Bulma framework, my goal is to align the height of the left column ...

Processing images with PHP from an array using AJAX

I have designed a straightforward form for image uploading. I am storing the properties of the uploaded images in an array, and my goal is to send this array to a PHP file using ajax. However, when I attempt to access the uploaded image using $_FILES[&apos ...

Draggable HighStock element causing issues with Gridster dragging

I have integrated a stocks chart from HighStocks with gridster, where each gridster block is draggable. However, the stocks time slider gadget can also be dragged and resized. When I move the slider on top of a gridster widget, the entire widget moves alon ...

Tips for customizing vue-bootstrap-datetimepicker: Adjusting width and adding icons for a personalized touch

I am working with two date pickers from the Vue Bootstrap DateTimePicker package. While the functionality is great, I need to modify their appearance. Here is the relevant code snippet: <template> <div> <div class="form-row"> ...

How to send emails in the background using a React Native app

I'm looking to incorporate email functionality into a React Native app so that it can send messages automatically when certain actions occur in the background. ...

NodeJS: Issue when implementing try/catch with async/await causing SyntaxError

As a newcomer to Node Js, I am struggling to understand why the code below is throwing a syntax error with catch(). I recently updated to Node JS V14. Any assistance would be greatly appreciated. async function demoPromise() { try { let message ...

What is the method with the greatest specificity for applying styles: CSS or JS?

When writing code like the example below: document.querySelector('input[type=text]').addEventListener('focus', function() { document.querySelector('#deletebutton').style.display = 'none' }) input[type=text]:focu ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

Determine the total cost based on the quantity purchased

I created a webpage for employees to select an item from a dropdown menu, and it will automatically display the price of that item. Check out my code below: <script> $(document).ready(function() { $('#price_input').on('change' ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

Having trouble with your HTML iFrame not functioning properly?

My code is not working as expected and I'm puzzled by it. It was working fine yesterday but now it's giving me trouble. <iframe allowfullscreen="" allowtransparency="true" frameborder="0" height="2000" scrolling="no" src="http://www.google.co ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

Repeated URL causes Node to redirect

I am currently working on a project that involves redirecting users if they enter a specific URL, especially for redirecting from a Heroku domain. During my testing phase on localhost, I noticed that the redirect URL keeps getting repeated: http://localh ...

The menu item fails to respond to clicks when hovering over the header background image

I'm having an issue with the Menu Link not working. I can click on the menu item when it's placed inside the body, but when I try to place it over the background header image, it stops working. Any help would be greatly appreciated. <div clas ...

increasing the size of the JSON object

I have a function that is being called multiple times utilizing jQuery to fetch different JSON data from an API. My aim is to calculate the total count of a specific portion of the JSON retrieved. Below is an example of what I currently have: getTheData( ...