Is there a way to delay the inner for loop and have the outer for loop wait until the inner loop has completed its iteration?

Is there a way to achieve this with delays? How can I coordinate the outer loop to wait for the inner loop to finish, and ensure that each iteration of the inner loop is delayed by 2 seconds? The desired outcome looks like this:

The outer loop will print in the console: 0

The outer loop will pause until the inner loop completes.

The inner loop will print: 0, 1, 2 with a delay of 2 seconds between each iteration.

Then the outer loop will print: 1.

The outer loop will again await the completion of the inner loop.

The inner loop will once more print: 0, 1, 2 with a 2-second delay between each iteration.

And so on.

for (var i = 0; i < 3; i++)
  {
    alert(i);
    for (var j = 0; j < 3; j++)
      {
        alert(j);
      }
    }

Answer №1

In a discussion about implementing synchronous delay in code, it was suggested to create a custom wait function and incorporate it into your script.

function pause(time) {
    var start = Date.now(),
        current = start;
    while (current - start < time) {
      current = Date.now();
    }
}

for (var x = 0; x < 3; x++)  {
  alert(x);
  for (var y = 0; y < 3; y++) {
    alert(y);
    pause(2000);
  }
}

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

Modify the color scheme of the Highcharts Maps to display a range of colors according to the minimum and maximum values

I'm currently working on a Vue project where I need to display data on a world map. However, I'm facing an issue with changing the color on the map. I want to utilize the minColor and maxColor options in the colorAxis configuration, but for some ...

Dealing with errors in promises

At times, when creating a promise, there may be unusual scenarios such as the database refusing the connection or an invalid host name parameter. For instance: In db.js const mysql = require('mysql'); module.exports.connect = (options) => { ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

Can we find a jQuery AJAX equivalent to the 'finally' block in regular JavaScript?

Is there an equivalent of Java's 'finally' in jQuery AJAX calls? I have this code snippet here. Inside my always, I intentionally throw an exception, but I want it to always proceed to the then() method. call.xmlHttpReq = $.ajax({ ...

JavaScript confirm function fails to validate a required field validator

Utilizing the required field validator to validate a text box and prompting for confirmation on the click of a submit button using the confirm() function in JavaScript has posed a challenge. Upon pressing OK in the confirmation box, the page refreshes an ...

Unable to find THREE.SpriteCanvasMaterial as a constructor in Angular 7

I am integrating THREE JS into my Angular 7 project using this code snippet from the official THREE website. However, upon running the project, I encountered the following error: core.js:15723 ERROR TypeError: THREE.SpriteCanvasMaterial is not a construct ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

The pictures in a <div> tag are not showing up

Functionality: I have set up 2 different <div> elements with unique IDs. Each of these <div> elements will make an ajax call to fetch a specific set of images for display. To summarize, both <div> elements are invoking the same ajax met ...

What is the best way to import API Endpoints from various directories in an Express Server?

I have been using a script to load my API endpoints like this: readdirSync('./routes/api').map((r) => app.use( `/api/v1/${r.split('.')[0]}`, require(`./routes/api/${r.split('.')[0]}`) ) ); This script reads eve ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...

Tips for setting a data-attribute on the body tag using the current route name in Vue

I have been considering adding a data-attribute to the body of my vue-app that would display the current route's name. I prefer not to utilize the vue-body-class package and want to keep it simple. Currently, I am implementing this in each of my main ...

Importing a JS class within a Vue.js script tag

I'm attempting to incorporate a JS file into the Vuejs script but for some reason, it's not working as expected. JS file class Errors { constructor() { this.errors = {}; } get(field) { if (_.has(this.errors, 'errors.' + ...

When attempting to fetch a file from a Node.js server using an Ajax call, the retrieved data appears to be cut off

I am facing an issue with downloading a file from a Node.js server (using Express). The request is being handled correctly and the response.download file is triggered on an existing file. However, when the data is received on the client side, not all of it ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

The functionality of this code is effective, however, it would be more efficient if it were implemented as a loop

While this code works, it has limitations. I believe adding some iteration would improve its functionality, but I am unsure of the best approach to take. For instance, how can I efficiently check 20 items instead of just 4, and have the flexibility to eas ...

Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

Tips for initializing the store in Vue when the application first starts

Seeking assistance in loading products from my pinia store upon the initial load of my Vue app. Check out my app.js below: import {createApp} from "vue"; import App from "./App.vue"; import router from "./Router/index"; impor ...

Can Handsontable be vulnerable to XSS without the use of PHP?

Despite my webpage having the php extension, there is actually no php code present on it. Instead, users are able to input numbers and experience some exciting JS effects through the integration of handsontable. While developing the comments section, I i ...

Selectize autocomplete causing a postback upon pressing the backspace key

Currently, I am integrating Selectize.js into my ASP.NET WebForms project. To enhance user experience, I am transforming an ASP.NET Server Side DropDown into an autocomplete dropdown using this plugin. This dropdown is connected to a DataSet with text and ...