"Creating a delay within a loop using the setTimeout function

When using setTimeout in a loop, I noticed that all the operations are executed only after the loop ends. I followed the advice from multiple articles and tried putting setTimeout in a separate function, but it didn't make any difference. Here is the simple code snippet:

function printNumber(i)
{
    setTimeout( function() {console.log(i);}, 2000);
}

for (let i=0; i<5; i++)
{
    printNumber(i);
}

Instead of printing the numbers one by one as expected, it prints them all at once:

0 1 2 3 4

Answer №1

The reason for this behavior is that the process registers all 5 setTimeout calls almost simultaneously.

To address this, you can try setting different timeout times like in the example below:

function foo(i)
{
    setTimeout( function() {console.log(i);}, 1000 * i);
}

for (let i=0; i<5; i++)
{
    foo(i);
}

Answer №2

Another approach would be using a generator to achieve the desired functionality. Generators allow functions to pause execution and then resume it later. Visit this link for more information on JavaScript generators.

function* customGenerator() {
    let count = 1;
    while (count <= 5) {
        yield count++;
    }
}

let g = customGenerator();

var interval = window.setInterval(function(){
  const result = g.next();
   if (result.done){
   clearInterval(interval);
   } else {
    console.log(result.value)
   }
}, 1000);

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

Can a value be concealed within a dropdown list on a form (using PHP or JavaScript)?

Within my form, there is a drop down box listing the 50 states in the U.S. This list is generated using a PHP for loop. Users are required to select their residential state and later on, they must also choose a mailing state if it differs from their resi ...

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

Tips for implementing the update function in a MEAN stack for a basic CRUD application

I am currently facing a roadblock while working on a basic MEAN CRUD Application. My struggle lies in the update part of the CRUD operation. I have included the function I've been working on below. Can anyone lend a hand, please? router.updateJob = f ...

vuejs default properties initialized with vue-i18n

I am trying to establish a default property from a dictionary in this way: props: { title: { type: String, default: this.$t("basic.confirm"), }, description: { type: String, } }, ... The $t function is part of the vu ...

Converting a String into a JSON Array

I currently have an array of JSON plots saved in MySQL. However, when I retrieve this information from the database, it is returned as a single long string. How can I convert this back into an array of JSON objects using JavaScript? My setup involves NodeJ ...

What is the best way to ensure the header and sidebar stay fixed while allowing the rest of the page content to flow in

I am working on a website where I want the header and sidebar to remain fixed while the other pages open in the remaining space. How can I make the sidebar dynamic? Here is an example of what I am trying to achieve: https://i.sstatic.net/MBFesWfp.png How ...

Transforming the color of a globe from black to white with gio js

After searching for a solution to change the color of a Three.js globe, I came across a link that didn't work as expected: Change the color of a Three.js globe. My goal is to change the globe color from black to white using . I attempted to use the f ...

Error message: Uncaught TypeError - Unable to retrieve data using POST method in react with node and express servers

I am currently working on creating a Login / Register form using react for the client-side and node / express / (mongo) for the backend. The backend functionality is working smoothly as expected, with successful storage of credentials in the database upon ...

Digital clocks created with Javascript for educational purposes, each displaying a unique image array for K-12 students

I am on the lookout for a script that can run a digital clock in a web browser using unique images for each digit. I plan to create a 'Maarten Baas' inspired clock with the children in my technology and design class. The kids will take on the ro ...

How can I trigger a jQuery click event from my ASP code behind?

The front end of this project has been completed and makes use of jQuery to handle user clicks. I have a radio button that triggers the event below when clicked. I want to ensure that this event is triggered for the HTML input element in my code behind dur ...

Effortlessly choosing and setting values in jQuery Select2

This particular code is meant for versions of Select2 prior to version 4. Here is a simple select2 code snippet that retrieves data via AJAX. $("#programid").select2({ placeholder: "Select a Program", allowClear: true, minimumInp ...

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Download files from Firebase storage to a user's device

I have a variety of files such as images, videos, and audio stored in my firebase storage. My goal is to provide users with the ability to download these files to their computers by clicking on a download button. After reviewing the firebase documentation ...

Can an inline try be implemented without including a catch block as demonstrated?

I have a scenario where I need to execute code that may result in an error without catching it. If the response is not valid JSON, then the desired outcome should be 0: Here is the code snippet I am considering: var overallProgress = try {JSON.parse(text ...

How to implement saving TypeScript Map() in Firebase Cloud Functions?

I am currently developing a Firebase Cloud Functions application using TypeScript that is designed to save an instance of Map() to Cloud Firestore. The map consists of user IDs as keys and objects with 2 simple attributes as values. Due to the dynamic natu ...

The script fails to function on elements contained within an infinite scrolling feature

I am facing an issue with my code after implementing infinite scroll. The like script seems to be broken as the page gets refreshed when I try to like a post. Here is the Like-btn script: <script> $(document).ready(function(){ ...

What steps should be taken in PHP to display a popup when the user input is found to be invalid?

I've been working on implementing a popup in PHP to show if the user enters an existing username, as per our teacher's requirement to use popUp instead of alert. I have set the visibility property of the popup to "Hidden" in CSS; <div class=&q ...

Script that was generated dynamically is failing to run

I have a situation where I am adding a script tag, along with other HTML content, to my current document after making an AJAX call. However, the script is not executing as expected. //Function to handle response function(responseText){ document.getEle ...

React window resizing actionsWould you like some more information on this

I am attempting to create a resize function that will retrieve the window width and dynamically display it using react. Here is my current code: class Welcome extends React.Component { constructor() { super(); this.state = { ...

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...