Is there a way to adjust a simple program using Discord.js where the setTimeout within a for-loop can print values sequentially instead of simultaneously?

Here is the code I'm using:

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

function delay(i) {
  setTimeout(() => console.log(`${i} is the number`), 2000);
}

The output I'm currently getting after 2 seconds is:

0 is the number

1 is the number

2 is the number

3 is the number

4 is the number

5 is the number

All of them print together immediately after 2 seconds, but I want each one to print after 2 seconds, like this:

0 is the number

(after 2 seconds)

1 is the number

(after 2 seconds)

2 is the number .....

Is there a way to achieve this desired delay in printing the numbers? Thank you!!

Answer №1

setTimeout is an example of a non-blocking function. The for loop does not pause to wait for the completion of delay, but instead immediately calls delay(i) six times consecutively.

To address this issue, one solution is to implement async/await and convert setTimeout into a Promise:

(async () => {
for (let i = 0; i <= 5; i++) {
    await delay(i);
}
})();

function delay(i) {
return new Promise(resolve => setTimeout(() => {
    console.log(`${i} is the number`);
    resolve();
}, 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

Refresh the Page or URL After Submitting a Form using JavaScript or PHP

Just a heads up: I'm fairly new to the world of web development. Currently, I'm in the process of crafting an event calendar using CodeIgniter. However, I've hit a bit of a snag. Whenever I try to update an event using JavaScript, the page ...

Perform an Ajax request upon clicking on the dropdown list item

I recently created a drop-down list using some JavaScript code. Here's how I did it: <script> $('.menu').dropit(); </script> <ul class="menu"> <li> <a href="#">Product_name</a> ...

Calculating the angle formed by three vectors in three-dimensional space

According to the solution(s) provided in this post Angle between 3 points in 3d space, there is a JavaScipt function that calculates the angles between three vectors in 3D space. The function calculates the angles as if each vector is a vertex on a surface ...

Using JavaScript build-in functions in a Vue template allows for enhanced functionality and

Is there a way to utilize JavaScript built-in functions within a Vue template? {{ eval(item.value.substring(2)) }} I attempted to use the JS function eval() in {{}}, but encountered several errors such as: [Vue warn]: Property or method "eval" i ...

(Express JS) What is the correct way to integrate another module into my router? (I am consistently encountering an undefined reference error)

I am currently working on a basic PDF reader application that utilizes the pdf.js library from Mozilla. The user is expected to select a file, after which the website should automatically redirect to the /reader page displaying the PDF. However, I am facin ...

Looking to convert files like text or images into binary format using Node.js?

I'm struggling to find a solution for converting any type of file (text, image, etc) into binary format using Node. Can anyone provide some guidance on how to accomplish this task? ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...

Eliminate the blank choice from X-editable Select

Lately, I've been dealing with AngularJS and X-editable and one thing that has been troubling me is the fact that the select option always includes an empty first child. Here's the HTML <span editable-select="curuser.roles" e-name="roles" ...

Integrating information from various sources to create a cohesive online platform

I am looking to incorporate data from various sources into a single web page: Social networks (Facebook, Twitter, LinkedIn, etc.) RSS feeds Article meta tags (particularly OpenGraph and Twitter cards) This data may change dynamically based on user inter ...

Encountering issues with configuring an Express server with HTTPS

Having difficulty setting up my Express server on HTTPS and accessing my API. Below is the code I am using: // server.js const express = require('express'); const { readFileSync } = require('fs'); const https = require('https' ...

Adding a navigation bar to every administrator page while excluding it from shop pages can be achieved by creating a

I am facing a challenge in implementing a navbar and sidebar on all admin pages, except for the shop page. The issue arises because I have set my sidebar and navbar to be global. My goal is to make them global only for admin pages and not for the shop. He ...

Unable to retrieve information from localhost site using the expressjs API. I have attempted to use both vue-resource and axios in order to get the data without success

Currently diving into the world of VueJS, I decided to embark on a project. My aim is to retrieve data from an ExpressJS server/API. But unfortunately, both vue-resource and axios have been returning status code 0. It seems like my API might not be handli ...

Triggering the creation of an Algolia Index from Firestore operations like updates, deletions, and additions is causing significant delays

I'm currently developing an application with Algolia integration and Firebase compatibility. To utilize Algolia's features, I have incorporated the firebase extension from this link. This allows for real-time synchronization of data between Fire ...

Guide to embedding an iframe generated with JavaScript into a React component

I'm currently working on developing an app that will utilize an iframe. The goal is to have controllers in place to adjust the style of the iframe and add text to it, essentially creating a preview function. I've been attempting to use Javascript ...

Conceal rows in the table until the search (filterBy) is completed

Currently, I am utilizing Vue.js version 1.x and plan to update soon. My requirement is to have a table of rows containing some data. To filter the table rows using filterBy, I am using a Vue.js component. However, I want the table rows to remain hidden un ...

Why does my dialog box only open the first time and not the second time?

I have created my own custom dialog box using jQuery and it seems to be working fine initially. However, after closing it once, when I try to open it again nothing appears. Can anyone help me identify what's causing this issue? Below is the source co ...

Can you tell me the specific name of the HTML document style that features two columns?

Here are two websites that showcase a unique two-column style layout: http://momentjs.com/docs/ I find these sites visually appealing and I am curious about the specific name of this style. Is there a template or tool available to create documents with a ...

Guide on making an AJAX post request to a modified URL

I am currently facing an issue where I am unable to submit a form to a PHP file via post method due to some problem with ajax. My query is, can I submit the form to a different URL if the backend has rewritten URLs? CURRENT PAGE URL: - actual: - re-wri ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...