Home > Software design >  How to create a delay in React.js
How to create a delay in React.js

Time:01-01

I am working on a webpage that visualizes sorting algorithms in React. The problem is, the changes all happen too fast and the massive array is organized in less than a millisecond. I need a way to delay the algorithm so that it stays on each change for half a second. I think changing the refresh rate might also work. Let me know if you think there are better solutions!

Either way, delaying the progress of the sorting algorithm through setTimouts has not been working. Neither has promises or awaits.

Here is an example of something I tried that didn't work:

setTimout(() => {
  swap(b, b-1) //swap is a separate method
}, 500)

CodePudding user response:

The code you posted would delay every swap by 500ms. But all of them still happen in succession without space in-between. It sounds like you want a delay between each swap so the sorting visualization is slowed down. Somehting like this pseudo-code might work:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function sortingAlgorithm() {
  while(/*not sorted yet*/) {
    swap(b, b-1)
    await sleep(500);
  }
}

  • Related