I'm attempting to showcase a nested countdown utilizing two nested loops.
You can access the complete, functional code on this js.fiddle link. Two key segments are highlighted below:
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main()
{
while(true)
{
clearScreen();
for (var i = 10; i > 0; i--)
{
print(i);
await sleep(1000);
clearScreen();
innerLoop(); // Refactored inner loop function call
}
}
}
async function innerLoop()
{
for (var j = 3; j > 0; j--)
{
print(j);
await sleep(1000);
clearScreen();
}
}
main();
While the initial code behaves correctly, the countdown does not function as intended when I move the inner loop to a separate function like this:
async function innerLoop()
{
for (var j = 3; j > 0; j--)
{
print(j);
await sleep(1000);
clearScreen();
}
}
and incorporate a function call inside main()
, resulting in the countdown failing to work as expected. (Refer to the code here: js.fiddle).
How can I ensure that async/await functions properly when nested within functions to achieve this? My goal is to avoid consolidating everything into a single extensive function.