Executing a setTimeout function within an Ajax call in a loop

I am attempting to execute a function after a delay of 1 second, but the function is triggered within an ajax call inside a foreach loop.

Code:

let index = 1;
portals.forEach(portal => {
    setTimeout(() => {
        $.ajax({
            type: "POST",
            url: url,
            async: false,
            success: function (data) {
                index++;
                text(index, total); // The goal is to call this function after a 1-second delay
            }
        });
    }, 1000);
});

However, it only triggers at the first and last iteration.

I have attempted placing the function inside an asynchronous function and using a promise to solve the issue, but it still doesn't work. Here is the alternative code I tried:

let index = 1;
const delay = (amount = number) => {
    return new Promise((resolve) => {
        setTimeout(resolve, amount);
    });
}

async function forPortals(){
    for(index; index<=total; index++){
        $.ajax({
            type: "POST",
            url: `/export/${portals[index].file}.php`,
            async: false,
            success: async function (data) {
                if(index>total){
                    text(index, total);
                    await delay(1000);

                }
            });
        }
    }
forPortals();
  • How can I trigger the text() function after a 1-second delay?

The desired outcome is for the function to be executed 7 times with a 1-second timeout each time.

Answer №1

To tackle this issue, I would implement an asynchronous forEach loop along with a delayed async function.

Here is the code snippet:

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    const asyncForEach = async function(array, callback) {
        for (let index = 0; index < array.length; index++) {
            await callback(array[index], index, array);
        }
    }

    const initialize = async () => {
        await asyncForEach(items, async (item) => {
            await wait(100);
            performOperation(index, total);
            index++;
            $.ajax({
                type: "POST",
                url: apiUrl,
                async: false,
            });
        })
    }
    initialize();

Answer №2

You have the ability to utilize this function for your needs, but please be aware that it may put a strain on your browser and cause high expenses.

function delay(milliseconds) {
    var start = new Date().getTime();
    while(true){
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

let counter = 1;
portals.forEach(portal => {
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            counter++;
            delay(1000);
            display(counter, total);
        }
    });
});

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

Received an error: xy is not defined, despite functionality being present

In my code, I am trying to update a value using this line of code: $('#'+name+userid).val(value); However, the userid variable seems to be undefined. I tried defining a new variable userid as a.attr('userid'), but then the value does no ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

The AJAX request result is returning blank

I currently have an input field set up as follows: <input type="email" name="email" required/> Upon clicking the submit button, it triggers the following function: $(".store_email").click(function() { var ajax_url_store_email = "store_email. ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...

Struggling with making /api/login/ function properly - using JavaScript and Reddit

Oh no, I've reached my limit of attempts... just received the message "you are doing that too much. try again in 27 minutes." So, I decided to come here and seek help. Here is the request I am making URL: http://www.reddit.com/api/login/ Headers: ...

Using a combination of different materials on a single mesh can lead to problems with z-index and clipping

Currently in my threejs project, I am attempting to apply two different materials to a mesh. One material has a solid color, while the other has a canvas texture. To achieve this, I have created both materials and added them to an array, which is then assi ...

Understanding how `io.use()` functions in socket.io authentication and session data sharing

After finding inspiration from an intriguing question on integrating sessions with Socket.IO 1.x and Express 4.x, I decided to implement socket authentication in a unique manner that eliminates the need for cookie-parser and header cookie reading. However, ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Could the delete button in a Chip component from Material-UI be customized with a unique style?

I'm having no issues styling the label or background color of the chip itself. However, it appears that the delete button inside the chip is an SVG icon. Is there a method to change the color of this icon? ...

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...

Whenever I attempt to start my ReactJS project using the command line with `npm run it`, I keep encountering an error

Encountered an issue with the webpack-dev-server script while working on my project. Ensure that your node.js and npm versions are up to date. If they are, the problem might lie within the reactjs package rather than npm itself. Kindly inform the author ab ...

How to use jQuery to locate a class within a parent div element

I'm attempting to modify the alt attribute of an image by clicking on it using the add_answer class. Note: The add_answer class is present in multiple div containers. jQuery(function(){ // Add Answer jQuery(".add_answer").click(function(){ ...

Using regex in JavaScript to perform destructuring assignment

My current task involves reordering a specific string of text, 'Set 1 Total Games Over/Under 9.5', using regex to make it read as 'Under/Over N Giochi Set 1'. The code snippet that achieves this is as follows: let marketLabel = 'S ...

Getting a specific nested child component from the parent component's slot in the render function: A step-by-step guide

I have successfully implemented conditional rendering of a child component using the render function. Below is an example of the parent component with the child component: <Parent :index="1"> <Child> ... </Child> <Child&g ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

Error: Attempting to access property 'baseHref' of an undefined value is not possible

Creating a webpack configuration for Angular 7 has been my recent project. I found a helpful tutorial on how to customize build configuration at this link. I decided to use the @angular-builders package for this task. Upon checking my index.html file, I m ...

Having trouble getting drag and drop functionality to work in Firefox with my current solution

I have successfully added drag and drop functionality to my website for images. The drag and drop feature is working well, but now I need to save the dropped images to the server. I have included image data as hidden elements in the view so that I can acce ...

"Exploring the Method of Inheriting from a BaseComponent in Angular 2

I’ve been working on an Angular project and I’m looking to streamline the creation of components with shared functionality. For example, let’s say I have a TeacherIndexComponent: @Component({ selector: 'app-teacher-index', templateUrl: ...

What is the reason behind the ineffectiveness of placing HTML5 canvas in the background?

I've been attempting to set an HTML5 canvas as my web page background, but I just can't seem to get it right. Can someone provide me with some guidance on how to achieve this? Here is the code from my latest attempt: <!DOCTYPE html> <ht ...

Utilizing a function upon page initialization in VueX

I am currently learning Vue with Vuex and I have created a method called 'llamarJson' which is used to retrieve JSON data. However, I am facing difficulties in using this method when the page loads. I have tried various approaches but have not be ...