我正在使用JS、HTML和CSS制作一個排序演算法的可視化工具,為了顯示氣泡排序,我寫了以下代碼
。for (let i = 0; i < element; 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) ) {
//如果元素需要互換,那么下面的代碼將改變其高度。
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[/span].
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;
}
但這里的問題是,我無法看到任何中間結果,比如看到兩個div被著色和改變高度。 我只能在排序完成后看到整個事情的排序。 那么這里的問題是什么? 如何解決這個問題?
uj5u.com熱心網友回復:
當你的代碼在運行時,UI并沒有更新(不會有任何渲染,否則網頁會閃爍,如果它們有動態內容被JavaScript更新的話!),所以你忙碌的等待除了浪費CPU周期外,什么都不會做。
使整個事情成為異步的,并使用超時來等待。const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))將為您提供一個異步函式,它可以在給定的時間內進行睡眠,然后您可以將您的代碼變成一個異步函式(因此您可以使用await)并使用await sleep(500) 而不是sleep(500) 。
由于代碼現在不再是同步的,它將不會阻塞事件回圈,并將允許 UI 在您等待時進行更新。
下面是一個異步等待的作業示例:
。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', () => {
///在這里捕捉任何異步錯誤是很重要的,這樣它就可以被處理。
//無論它發生在流程中的哪個位置--否則它將成為。
///一個未處理的承諾拒絕。
count().catch(span class="hljs-params">e => console. error('An error occured during counting!', e))
})
<h1 id="counter" > . ...</h1>。
<button id="count-button">/span>Count! </button>/span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/320424.html
標籤:
