Nested functions with async-await syntax

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.

Answer №1

Ensure to use the await keyword when calling the innerLoop() function since it is declared as an async function:

var containerElement = document.getElementById("container");

function print(string) {
  var textDiv = document.createElement("div");
  textDiv.textContent = string;

  containerElement.appendChild(textDiv);
}

function clearScreen() {
  containerElement.textContent = "";
}

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();

      await innerLoop();  // <-- Await innerLoop()
    }
  }
}

async function innerLoop() {
  for (var j = 3; j > 0; j--) {
    print(j);

    await sleep(1000);

    clearScreen();
  }
}

main()
<!DOCTYPE html>
<html>

<body>

  <div id="container"></div>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript to implement an onclick function in a React JS component

In my React JS application, I am using the following code: <button onClick={tes} type="button">click</button> This is the tes function that I'm utilizing: const tes = (id: string) => { console.log(id) } When hovering ov ...

Updating the component's state based on the server response

Injecting the props into the initial state of a component is something I'm working on. The goal is to update the state and have the data reflected immediately when a button inside the component is clicked. The eventData object contains two attributes ...

Is it possible to synchronize functions in node.js with postgresql?

I’m facing some challenges in managing asynchronous functions. Here is the code snippet that's causing the issue: var query = client.query("select * from usuario"); query.on('row', function(user) { var queryInterest = client. ...

Is it possible to distinguish and identify each separate window when a user opens multiple instances of your site?

Has anyone explored the possibility of distinguishing between multiple windows a user may open on the same site? My goal is to assign the initial window the name "window1" and subsequent windows "window2" and so forth. Is there a method for achieving this ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

Step-by-step guide on adding a gallery image in Node.js

I need help with posting my gallery image to a nodeJs server. Here is the code I am currently using: vm.getImageSaveContactInst = function() { var options = { maximumImagesCount: 1, // Only selecting one image for this example width ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

using javascript to trigger android function

Looking to create a button in HTML that triggers a call from an Android device via JavaScript. Here is the code snippet I have tried, but it's not functioning as expected. Please note, I am new to Android development: public class MainActivity extend ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

Data retrieval is currently not functioning, as React is not displaying any error messages

One of the components in my app is as follows: import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { translate ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Switching Vue.js from the standalone build to the runtime-only build midway through a project?

Opted for the runtime-only version of Vue.js for a new project. I came across in the documentation that to switch to the standalone version, one must include an alias in webpack like this: resolve: { alias: { 'vue$': 'vue/dist/vue.js& ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Storing the created .wav file on the server using PHP

Is there another way to handle this? How can I manage streaming of a WAV file? I'm currently working on a platform that allows users to create their music compositions and the system outputs a .wav file for each creation. While I can play the mus ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

JQuery is facing difficulty in animating a div following the completion of a "forwards" css animation

Check out this example: http://jsfiddle.net/nxsv5dgw/ A div appears on the stage and a CSS animation is applied to it. However, when attempting to use JQuery to animate the same properties that were animated by CSS, it seems to no longer work properly. ...

Validating multiple fields that are added dynamically using jQuery

I am facing an issue with form validation using jQuery. The problem is that when one field is valid, the form gets submitted automatically. Here is a link to my code: http://jsfiddle.net/cvL0ymu7/. How can I ensure that all fields are validated before subm ...

Are $(function() { }) and $(document).ready(function() { }) the same function under the hood?

Similar Question: What sets apart these jQuery ready functions? Do $(function(){}); and $(“document”).ready(function(){}); have the same meaning? Beginning javascript code with $(function, etc. This day, as I was examining some jav ...