[英]Wait for click event inside a for loop - similar to prompt()
這可能沒有最大的標題。 我試圖理解回調函數,我想知道如何在不丟失for循環的情況下實現以下代碼中的hint()替換?
for(i=0;i<4;i++){
let x = prompt("Input an integer");
// store input into an array
}
我已經嘗試過類似的東西:
for(let i = 0; i<4; i++){
let x = document.getElementById("someId");
x.addEventListener("click", rcvInput(function(i){
if(i == 3){
x.removeEventListener("click", rcvInput)
}
}));
}
function rcvInput(callback){
//store input into an array
callback();
}
我知道這可以在沒有for循環的情況下完成,我很好奇回調是否可以暫停循環並等待輸入?
根據您的最終目標,我很確定有更好的方法來做到這一點。 但是為了做到這一點:
您可以創建一個返回承諾的方法,該承諾會在單擊發生時解決。 然后,您可以使用async
/ await
執行所需的操作。
通過使用Promise
並await
它,您可以從技術上“暫停”您的for
循環,直到發生某些事情為止。 在這種情況下,請單擊。
請記住,包含for
循環的方法必須是async
。
function getClick() {
return new Promise(acc => {
function handleClick() {
document.removeEventListener('click', handleClick);
acc();
}
document.addEventListener('click', handleClick);
});
}
async function main() {
for (let i=0;i<4;i++) {
console.log("waiting for a click", i);
await getClick();
console.log("click received", i);
}
console.log("done");
}
main();
在這個笨拙的人中嘗試一下。
實現:
for(var i=0;i<4;i++){
let x = prompt("Input an integer"); // WAIT FOR PROMPT
// ...
// LOOP CODE AFTER PROMPT
}
您可以使用遞歸:
function promptLoop(count){
let x = prompt("Input an integer");
// ...
// LOOP CODE AFTER PROMPT
if (count > 0) promptLoop(count - 1)
}
並像這樣使用它:
promptLoop(4);
您的第二種情況不同,可以像這樣進行調整:
function loop(count, method) {
if (count > 0) method(() => loop(count - 1, method), count);
}
然后,您的函數將執行下一個回調,如下所示:
function toBeLooped(next){
// do stuff
next() // continues loop
}
loop(3, toBeLooped);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.