How come my function is executing right away despite the setTimeout() being called?

I am working on a program that is designed to showcase how a bubble sort works. However, I would like the program to pause for one second after each swap in order to clearly demonstrate the sorting process. Below is the code I have written:

function bubbleSort(arr){
    for(var i = 0; i < arr.length-1; i++){
        for(var j = 0; j < arr.length-i-1; j++){
            if(arr[j] > arr[j+1]){
                swap(arr,j,j+1);
            }
        }
    }
}

Here is the swap function I am using:

async function swap (arr,a,b){
    var temp = arr[a];
    var temp2 = arr;
    temp2[a] = arr[b];
    temp2[b] = temp;
    await setTimeout(updateText(),1000);
    return temp2;
}

This is the updateText function being called:

function updateText(arrayText){
    document.getElementById('arrayText').innerHTML = printArray(arr);
}

When I run the bubbleSort() function, I notice that my array goes from unsorted to sorted instantly without showing the individual swaps. The updateText() function is only triggered within the swap function and nowhere else. I would appreciate any assistance or guidance on how to achieve the desired effect of displaying each swap before reaching the final sorted array.

Answer №1

The challenge lies in the fact that the setTimeout function does not inherently provide a promise to fulfill the requirement of await.

function resolveAfter1Second() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 1000);
  });
}

async function swapElements (arr,a,b){
    var temp = arr[a];
    var tempArr = arr;
    tempArr[a] = arr[b];
    tempArr[b] = temp;
    await resolveAfter1Second();
    return tempArr;
}

Answer №2

Check out this code snippet that demonstrates the bubble sort algorithm with a twist. Instead of just logging the array to the console, you can customize it to trigger a webpage update.

const waitFor = (delay) => new Promise((resolve) => setTimeout(resolve, delay));

async function bubbleSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        await swap(arr, j, j + 1);
      }
    }
  }
}

async function swap(arr, a, b) {
  [arr[a], arr[b]] = [arr[b], arr[a]]
  console.log(arr);
  return waitFor(1000);
}

const array = [10, 9, 4, 5, 3, 1, 2];
bubbleSort(array);

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

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

Something seems to be preventing Div from appearing and there are no error messages appearing

I've been attempting to create a menu, but the toggle div for the menu isn't visible Following a tutorial where an individual sets up a menu, there is a div with a menu icon in the top left corner. Despite meticulously copying the code from the ...

What's the best approach for implementing TimeInput exclusively in React-Admin?

I discovered this helpful code snippet on the React-Admin documentation that allows me to input both a date and time: import { DateTimeInput } from 'react-admin'; <DateTimeInput source="published_at" /> But now I'm wonderin ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

Retrieve an array of information from a firestore database query

I am encountering an issue while trying to retrieve information about all users who are friends of a specific user. I have attempted to gather the data by pushing it to an array and then returning it as a single JSON array. However, it seems that the dat ...

I have implemented a code snippet that verifies if the incoming week aligns with the existing week, triggering an alert accordingly

One of the challenges I faced was checking if a newly created week matched with an existing one, and then displaying an alert. Here's how I approached it: $scope.addWeek = function(type,newWeek,index){ var c = $scope.weekList.length + 1; var ...

jQuery fieldset.change is a feature that allows you to manipulate

I'm looking to update the value of a button when a radio button is clicked. <fieldset id="product-color"> <input type="radio" id="red" name="color" value="Red"> <label for="red">Red</label><br> <input typ ...

Implementing server-side pagination with Ngrx and using router parameters to navigate pages

In my store, I have a simplified state tree structure: { routerReducer: { state: { url: '/blog' }, queryParams: { category: 'home' } params: { } }, blog: { ...

The issue with property unicode malfunctioning in bootstrap was encountered

I have tried to find an answer for this question and looked into this source but unfortunately, when I copy the code into my project, it doesn't display Unicode characters. section { padding: 60px 0; } section .section-title { color: #0d2d3e ...

"Can you explain the functioning of this Node.js middleware when it doesn't require any

Currently, I am utilizing a function created by another individual for express and passport, which defines the middleware in the following manner: function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); } els ...

Vue Router Issue: Unable to Navigate to Different Routes, Always Redirected to Home Page

I am currently working on a Vue 3 project and am facing an issue with the Vue Router not displaying the correct routes. Whenever I try to navigate to routes such as /cars or /admin, the URL does not update and the application stays on the home page. import ...

var numerous occurrences of an angular service

In accordance with the document, Angular services are considered singleton instances. I am currently developing a time-tracking project where I intend to incorporate multiple tasks. <ul> <li ng-repeat="item in data track by $index" > ...

Can you explain the contrast between `/:foo*` and `/:foo(.*)` when used in express routes?

When using Express, it is possible to define endpoints with different paths: app.get('/:foo*', function(req, res) { ... }); app.get('/:foo(.*)', function(req, res) { ... }); Although these two paths may appear similar, what sets them ...

What is the process for including a class along with a data attribute?

Working on implementing data buttons, struggling to make the function operational. Attempting to assign a class to an element through a data attribute and corresponding ID, then wanting to prevent event propagation with the button contained within the subj ...

What is the purpose of setting the Z-Index on a Popper menu

If you want to see a live example demonstrating the issue, head over to codesandbox.io. My goal is to create a 'sit below' menu just like it's shown in the Material-UI documentation here. return ( <div className={classes.root}&g ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

The response from the Whatsapp-web-js API can be delayed

As I work on creating an API to retrieve groupChat IDs using the express framework and whatsapp-web-js library, I've encountered an issue. The initial request to the endpoint after starting the server yields a response within 31 seconds, but subsequen ...

JSON format is used for returning values from WebMethod calls

How can I retrieve values from a Webmethod and format them in JSON for the client? I have two static int values that need to be returned. Do I have to create a new object with these properties each time, or is there a more efficient way to handle this? Th ...

As I iterate through a MySQL array, JavaScript is able to manipulate the initial displayed data

I'm struggling to achieve the desired outcome with my code. It seems that when I iterate through an array of data, JavaScript only works on the first echoed data. Here is a snippet of the code: <?php $ids = array(); ...