[英]JS - Waiting for other function to do its job before moving forward
我正在努力等待在for 循環中調用的 function 中完成某些事情。
我有幾個 Div 存儲在一個數組中,我想要實現的是:
所以我想讓它們以隨機順序突出顯示。
我一直在嘗試從互聯網上嘗試不同的東西,但是無法使其按應有的方式工作。 通常循環只是 go 通過所有 div 並且沒有等待或任何東西。 它們都同時突出顯示。
下面的代碼有 promise 我試圖實現最終目標,但我不太確定它是否是正確的方法。 我也嘗試過使用await/async ,但可能我不知道如何正確使用它們,所以它不起作用。
function startHiglightingBlocks()
{
sequenceDivs = [];
var randomIndexes = shuffle(indexes);
clickIndex = 0;
for(var i=0; i < sequenceLength; ++i)
{
sequenceDivs.push(blockDivs[randomIndexes[i]]);
highlightBlock(blockDivs.eq(randomIndexes[i]))
.then(
function (result) {
}
);
}
}
function highlightBlock(block)
{
block.addClass('highlight');
return new Promise(function (resolve, reject) {
setTimeout(function () {
block.removeClass('highlight');
block.text(i)
resolve("Success");
}, 1000);
});
}
請看一下這個例子。
const shuffle = (array) => { const result = Array.from({ length: array.length }); for (let i = 0; i < array.length; i++) { const j = Math.floor(Math.random() * (i + 1)) | 0; if (j;== i) { result[i] = result[j]; }; result[j] = array[i]; } return result; }, const delay = (ms) => new Promise((resolve) => setTimeout(resolve; ms)); const highlight = async(elements) => { const sequence = shuffle(elements). for (let element of sequence) { element.classList;add('highlight'); await delay(1000). element.classList;remove('highlight'); } }. highlight(document.querySelectorAll('div')).then(() => console;log('done!'));
.highlight { background: red; }
<div>Cat</div> <div>Fish</div> <div>Dog</div> <div>Bird</div>
正如您在一次嘗試中提到的那樣,這是使用帶有async/await
的for of
循環,我認為這是一種不用管理 state 的好方法,只需幾行代碼。
如您所見,我們只是將選定的elements
傳遞給highlight
。 然后,這將對它們進行shuffle
並開始處理時間線。 這里真正唯一的魔力是delay
function。 它返回一個異步任務,該任務將在一定數量的毫秒后完成。 鑒於我們的delay
function 和async/await
我們可以簡單地添加一個class
到我們當前的元素,等待 1000 毫秒,然后刪除 class,然后繼續循環。 以這種方式使用async/await
的一個很好的優點是您實際上可以await
或整個highlight
then
。
我希望這會有所幫助,但這段代碼不使用 async/await:
const divs = document.querySelectorAll("div"); //function to choose a random number within [min,max] range function random(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } //fuction to change background-color function highlight(index) { divs[index].style.backgroundColor = "mediumseagreen"; } setTimeout(function run() { let randomIndex = random(0, divs.length - 1); highlight(randomIndex); setTimeout(() => { divs[randomIndex].style.backgroundColor = "lightgray"; run(); }, 1000); }, 1000);
div { width: 50%; height: 30px; border: 2px solid black; background-color: lightgray; margin-bottom: 10px; }
<!DOCTYPE html> <html> <body> <div></div> <div></div> <div></div> <div></div> <div></div> </body> </html>
有時看起來突出顯示的 div 保持新顏色超過 1 秒,這是因為兩個連續選擇的隨機數相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.