简体   繁体   English

减慢 while 循环内的 for 循环(Javascript)

[英]Slow down for-loop inside while-loop (Javascript)

So I'm trying to visualize a sorting algorithm in Vanilla JS and for this I need the actual sorting function to not sort it all in the fraction of a second but to wait eg 250ms after each iteration.所以我试图在 Vanilla JS 中可视化排序算法,为此我需要实际的排序函数,不要在几分之一秒内对它进行排序,而是在每次迭代后等待 250 毫秒。 This is the Bubble Sort code (which does work):这是冒泡排序代码(确实有效):

function sortArray(){
    let arr = inputArray; //arr is the array to get sorted.
    let l = arr.length;
    let swapped;
//---Bubble sort---
    do {
        swapped = false;
        for (let i = 0; i < l-1; i++) {
            if (arr[i] > arr[i+1]){
                let temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
                swapped = true;
            }
        }
    }while (swapped);
//---Bubble sort---

    display.innerText = JSON.stringify(arr); //Display the sorted Array to the user
}

Now I researched on how to slow down a loop in JS and tried a couple of different ways.现在我研究了如何减慢 JS 中的循环并尝试了几种不同的方法。 For example:例如:

function sortArray(){
    let arr = inputArray; //arr is the array to get sorted.
    let l = arr.length;
    let swapped;
//---Bubble sort---
    do {
        swapped = false;
        for (let i = 0; i < l-1; i++) {
            setTimeout(() =>{
                if (arr[i] > arr[i+1]){
                    let temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                    swapped = true;
                    n++;
                }
                arrayDisplay.innerText =JSON.stringify(arr);
            },250 *i);
        }
    }while (swapped);
//---Bubble sort---

    display.innerText = JSON.stringify(arr); //Display the sorted Array to the user
}

Here I tried to use the setTimeout function inside the for-loop which does theoretically work but it does only slow down and display each step for the for-loop but stops after each run instead of looping again (while(swapped))(obviously, but I don't know how to fix it).在这里,我尝试在 for 循环中使用 setTimeout 函数,该函数在理论上可行,但它只会减慢速度并显示 for 循环的每个步骤,但在每次运行后停止而不是再次循环(while(swapped))(显然,但我不知道如何解决它)。 For each while loop I to press the button again.对于每个while循环,我再次按下按钮。

I also tried wrapping the whole do-while construction inside the setTimeout and add an additional set Timeout inside the for-loop.我还尝试将整个 do-while 结构包装在 setTimeout 中,并在 for 循环中添加一个额外的 set Timeout。 That simply crashed my browser.那只是让我的浏览器崩溃了。 I also tried a couple of other constellations but those also either crashed the browser or didn't sort at all.我还尝试了其他几个星座,但那些也使浏览器崩溃或根本没有排序。

setTimeout() creates an asynchronous process but for and while loops normally runs synchronously, so it doesn't work to do it like that. setTimeout()创建了一个异步进程,但是forwhile循环通常是同步运行的,所以它不能像那样做。 If your environment supports async-await syntax, you can use that to make for and while run asynchronously.如果您的环境支持async-await语法,您可以使用它来使forwhile异步运行。

Annotate the function as async , promisify the timeout and then await it, like this:将该函数注释为asyncpromisify超时,然后await它,如下所示:

async function sortArray(){
    let arr = inputArray; //arr is the array to get sorted.
    let l = arr.length;
    let swapped;
//---Bubble sort---
    do {
        swapped = false;
        for (let i = 0; i < l-1; i++) {
            await new Promise(resolve => setTimeout(() =>{
                if (arr[i] > arr[i+1]){
                    let temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                    swapped = true;
                    n++;
                }
                arrayDisplay.innerText =JSON.stringify(arr);
                resolve();
            }, 250));
        }
    }while (swapped);
//---Bubble sort---

    display.innerText = JSON.stringify(arr); //Display the sorted Array to the user
}

If your environment doesn't support async-await , you're going to need to use a more complex approach with callback functions instead of for and while loops.如果您的环境不支持async-await ,您将需要使用更复杂的回调函数方法而不是forwhile循环。

Keep in mind that an async function will always return a Promise .请记住, async函数将始终返回Promise It's not relevant in this case since your function creates side-effects and doesn't return anything.在这种情况下它不相关,因为您的函数会产生副作用并且不返回任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM