Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
El código JavaScript se ejecuta al mismo tiempo y no espera

Estoy haciendo un visualizador de clasificación en javascript. Este es un ejemplo de uno de los algoritmos de clasificación: clasificación por selección Pero cuando ejecuto el código, incluso si las funciones Visualizer.Compare y Visualizer.Swap de clasificación por selección tienen pausas de 1 segundo, la matriz se ordena instantáneamente en lugar de hacer una pausa. Creo que esto se debe a que javascript ejecuta asincronía porque si, en cambio, creo el código que cambia las alturas de las barras en un tiempo de espera, se ejecuta normalmente, excepto que después de que el tiempo de espera ha pasado, todas las alturas se cambian al mismo tiempo, lo cual es extraño.

todo el código se ejecuta agregando un evento al hacer clic en un botón que ejecuta la función selectionSort cuando se hace clic (código github https://github.com/Jalrux/sorting-visualizer )

 function selectionSort(array, visualizer) { let arrayLength = array.length; let minIndex; // loop through the array and sort each value array for (let i = 0; i < arrayLength; i++) { // loop through all indexes of array minIndex = i; // assume that element with i index is minimum // Find the minimum element in unsorted array for (let j = i + 1; j < arrayLength; j++) { // loop through indexes of unsorted elements visualizer.compare(i, j); // run the comparing visualizer if (array[minIndex] > array[j]) { // check if the element of minIndex is larger than value of the index j minIndex = j; // set minIndex to j } } visualizer.swap(minIndex, i); // run the swapping visualizer let temp = array[i]; // Swap the minimum element with element of index i array[i] = array[minIndex]; array[minIndex] = temp; visualizer.finished(i); // change the color of the bars at index minIndex to the finished color } } export {selectionSort, generateArray};

Este es el código para la función de intercambio en el archivo visualizador.js

 // change the colors of 2 bars to the swapping color and swap export function swap(index1, index2) { let bar1Style = arrayBars()[index1].style; let bar2Style = arrayBars()[index2].style; // save the previous colors let bar1Color = bar1Style.backgroundColor; let bar2Color = bar2Style.backgroundColor; // change the colors to the comparing color bar1Style.backgroundColor = swapColor; bar2Style.backgroundColor = swapColor; // swap the heights of the bars pause(); let bar1height = bar1Style.height; let bar2height = bar2Style.height; bar1Style.height = bar2height; bar2Style.height = bar1height; pause(); // change the colors back to their original colors bar1Style.backgroundColor = bar1Color; bar2Style.backgroundColor = bar2Color; } // some helper functions that are in the visualizer.js file export function arrayBars() { return document.getElementsByClassName('array-bar'); } // sleeps for pauseTime seconds export function pause() { setTimeout(function() {}, pauseTime); }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Tal vez use un retraso basado en promesas con async/await .

 function delay(time) { return new Promise(res => { setTimeout(() => res(), time); }); } async function main() { console.log('First... waiting for two seconds'); await delay(2000); console.log('Second... waiting for five seconds'); await delay(5000); console.log('Done'); } main();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda