Tips for getting the setTimeout() function to behave like a for loop

Is there a way to achieve the setTimeout() function's behavior in a for-loop? Take a look at this code snippet:

function hello() {
    for (let index = 0; index < 3; index++) {
        setTimeout(function () {
            console.log('What\'s up!')
        }, 3000)
        console.log('Yo')
    }
}

hello()

The output of this code is:

Yo
Yo
Yo
What's up!
What's up!
What's up!

How can we modify it to log like this:

Yo
What's up(after 3 sec)
Yo
What's up(after 3 sec)
Yo
What's up(after 3 sec)

Thank you for your assistance.

Answer №1

Here is one approach:

function greet() {
    for (let count = 1; count <= 3; count++) {
        setTimeout(function () {
            console.log('Hello!')
        }, 3000 * count)
        setTimeout(function () {
            console.log('Hi')
        }, 3000 * (count - 1))
    }
}
greet()

In this solution, I utilized the for loop index to provide a unique delay for each console.log statement. Notice how "Hi" always precedes "Hello!" by 3000 ms.

Answer №2

To tackle tasks like this, you'll need the power of either a Promise or the elegance of recursion.

Using Promise (without async/await)

async function hello(index = 0) {
    if (index >= 3) return;
    
    index += 1;

    return new Promise(function(resolve){
    
      setTimeout(function(){
        console.log('What\'s up!');
        resolve();
      }, 3000);
      
      console.log('Yo');
      
    }).then(hello.bind(null, index));
}

hello()

Utilizing Promise (with async/await)

async function hello() {
    for (let index = 0; index < 3; index++) {
        await Promise.all([
          new Promise(function(resolve){
            setTimeout(function(){
              console.log('What\'s up!');
              resolve();
            }, 3000);
          }),
          console.log('Yo')
        ]);
    }
}

hello()

Embracing Recursion

function hello(index = 0) {
    if (index >= 3) return;
    
    setTimeout(function(){
      console.log('What\'s up!');
      hello(index);
    }, 3000);
    
    console.log('Yo');
    
    index++;
}

hello()

PS: The scripts above are tailored for use with ES2017 and newer versions.

Answer №3

No matter how short the waiting time, using setTimeout() may not produce the desired outcome. It is recommended to either include both console.log statements within setTimeout(), or simply remove it altogether.

Answer №4

If you're looking for a solution, here's one that could help:

let counter = 3;
var num = 0;

function logHello(){
  console.log('Hello');
  logGoodbye();
}

function logGoodbye(){
  setTimeout(() => {
    console.log('Goodbye');
    num++;
    if(num < counter)
      logHello();
  }, 3000);
}

logHello();

Answer №5

One simple solution is to create a self-executing function using setTimeout(), however, it requires implementing a global counter variable.

let count = 0;
function greet(num){
    console.log("Hello");
    console.log("How are you?");
    count++;
    if(count > num){
        setTimeout(greet, 3000);
    }
}

Answer №6

If you're looking to display a new pair of logs every 3 seconds, take a peek at this code snippet utilizing async/await and promises:

async function greet() {
    for (let i = 0; i < 3; i++) {
        console.log('Hello');
        await new Promise(resolve => {
            setTimeout(function () {
                console.log('How are you?');
                resolve();
            }, 3000);
        });
    }
}

greet();

Before implementation, ensure that the browsers you aim to support can handle async/await and Promises by checking out resources like caniuse.

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

Is there a method to programmatically identify enterprise mode in IE11?

Is it possible to detect Internet Explorer 11 Enterprise mode programmatically? This would involve detecting at the server side using C# or JavaScript/jQuery. The discussion on the following thread has not reached a conclusive answer: IE 11 - Is there a ...

What method is best for deleting an item from the database in HTML structure - POST, GET, or XHR action?

I have a webpage that displays content in a table format and allows users to delete a specific row by clicking on it. The structure of my rows is as follows: foreach ($rewards as $reward) { echo '<tr id="' . $reward[&apos ...

Tips for guaranteeing blocking within a loop in Node.JS

While I usually enjoy the asynchronous nature of Node.JS and its callback-soup, I recently encountered an issue with SQLite that required a certain part of my code to be run in a blocking manner. Despite knowing that addressing the SQLite problem would mak ...

Building a basic music player with the <audio> element and JavaScript / jQuery

I am new to Javascript and jQuery, and this is my first time posting a question here. I have been trying to create custom functions for the HTML5 audio tag by following tutorials online. Despite my efforts, I cannot seem to get it working. Although I can m ...

Issue encountered while performing an Upsert operation on Pinecone using Node.js

Oops! PineconeArgumentError: The argument provided for upsert contains type errors: the argument should be an array. Package "@pinecone-database/pinecone": "^1.0.0", Inquiry const index = pinecone.Index(process.env.PINECONE_INDEX_NAME ...

AngularJS Update Parent-Child Relationship: Enhancing the Details

When Panel header is clicked, I want to update the respective Panel body with the corresponding data. In my Angular code on Plunker, clicking "Test1" should only update "Test1detail" in the body. Click here for the Plunker Here's the code snippet fr ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

I am hoping for the outcome to be directed to the homepage

I'm struggling to figure this out, as I am new to classic ASP and JavaScript. I hope someone can help me understand. I want to display the response.write on the main.asp (or the result) page, but each time I try, it redirects to pass.asp on a differen ...

Guide to modifying CSS properties of an individual element by manipulating class names with JavaScript

I have been searching for an answer to my question without success. I have a unique challenge where I need to change the styles of an h1 element by adding a class based on which radio button is clicked. The issue I'm facing is that when I select a dif ...

Issue arises when trying to set object members using a callback function in Typescript

I am facing a peculiar issue that I have yet to unravel. My goal is to display a textbox component in Angular 2, where you can input a message, specify a button label, and define a callback function that will be triggered upon button click. Below is the c ...

Utilizing Promise.all to update subdocuments with Mongoose

Encountered an error while checking the value in promiseArr, seeking assistance or suggestions for a better approach. Thanks! **Error** <rejected> { MongooseError: Callback must be a function, got [object Object] at new MongooseError (D:\P ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

I am able to input data into other fields in mongoDB, however, I am unable to input the

I am facing an issue with the password while everything else seems to be working fine. I am using a schema and getting an error, but it could be a problem in my functions because I hashed the password. I am unable to identify what's causing the issue. ...

Child object in Three.js does not inherit transformation from its parent

Consider a scenario where there is a main object with multiple child objects in a given scene. Update: Here is the code snippet for creating a mesh (assuming the scene and camera are already set up). Code snippet for creating the parent group: var geome ...

Strange glitch in the rendering of rectangles on HTML5 canvas?

While experimenting with pre-rendering sprites using HTML5 canvas, I encountered some strange behavior that appears to be a rendering bug. The issue can be seen in the following minimal example: var CT = document.getElementById("myCanvas").getContext("2 ...

What steps can I take to ensure that WebStorm properly recognizes a package's functions?

No matter what I do, WebStorm refuses to stop throwing inspection warnings when I try to use the JOI package in my node.js project. The code runs fine and there are no runtime errors, but the warning persists. I have updated the package, explicitly install ...

I am unable to give back an item

I am working with an object structure that looks like this: const obj = { name: 'john', children: [ { name: 'Foo' }, { name: 'Bar', children: [ { name: 'Doe' ...

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...