Estoy haciendo un visualizador de algoritmos de clasificación usando JS, HTML y CSS y para mostrar la clasificación de burbujas he escrito el siguiente código
for (let i = 0; i < elements; i++) { for (let j = 0; j < elements; j++) { let a = temp[i].style.height; let b = temp[j].style.height; //this is to show the current elements begin compared temp[i].style.backgroundColor = 'green'; temp[j].style.backgroundColor = 'blue'; if (parseFloat(a) < parseFloat(b)) { //if the elements need to be swapped then the following code will change its height let t = a; temp[i].style.height = b; temp[j].style.height = t; } //this is to slow down the process sleep(500); //this is to change back the div's background to normal temp[i].style.backgroundColor = 'white'; temp[j].style.backgroundColor = 'white'; } } } function sleep(num) { var now = new Date(); var stop = now.getTime() + num; while (true) { now = new Date(); if (now.getTime() > stop) return; } }pero aquí el problema es que no puedo ver ningún resultado intermedio como ver dos divs siendo coloreados y cambiando de altura. Solo puedo ver todo ordenado cuando se realiza la clasificación Entonces, ¿cuál es el problema aquí? ¿Cómo resolver esto?
Mientras su código se está ejecutando, la interfaz de usuario no se actualiza (no habrá ninguna representación, de lo contrario, las páginas web parpadearían si JavaScript actualizara contenido dinámico), por lo que su espera ocupada no hará más que desperdiciar ciclos de CPU.
Haga que todo sea asíncrono y espere usando un tiempo de espera: const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) le dará una función asíncrona que duerme durante la cantidad de tiempo dada, y luego puede hacer su código es una async function (para que pueda usar await ) y use await sleep(500) en lugar de sleep(500) .
Dado que el código ya no es sincrónico, no bloqueará el bucle de eventos y permitirá que la interfaz de usuario se actualice mientras espera.
Aquí hay un ejemplo práctico de espera asincrónica:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) const counter = document.getElementById('counter') const countButton = document.getElementById('count-button') async function count () { countButton.disabled = true counter.innerText = 'One...' await sleep(1000) counter.innerText = 'Two...' await sleep(1000) counter.innerText = 'Three...' await sleep(1000) counter.innerText = 'Done!' countButton.disabled = false } countButton.addEventListener('click', () => { // It's important to catch any asynchronous error here so it can be handled // regardless of where it happens in the process - otherwise it will become // an unhandled promise rejection. count().catch(e => console.error('An error occured during counting!', e)) }) <h1 id="counter">...</h1> <button id="count-button">Count!</button>