Issue with implementing setTimeout on await fetch() result

I'm trying to figure out how to add a setTimeout to my request response when using await fetch. Currently, each response is being sent to a DIV in the HTML, but I want to introduce a delay of 5 seconds before each response appears.

I attempted this solution, but unfortunately, it didn't work for me.

const envSoli = async () => {
    try {
      const controller = new AbortController();
      const signal = controller.signal;
      const timeId = setTimeout(() => {
        controller.abort();
      }, 20 * 1000); // 20 sec
      let peticion = await fetch("data.php", {
        method: "POST",
        body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
        headers: { "Content-type": "application/x-www-form-urlencoded" },
        cache: "no-cache",
        signal: signal,
      });
      clearTimeout(timeId);
      const oreen = await peticion.json();
      const takeAMoment = setTimeout(() => {
        switch (oreen.enviando) {
            case -1:
              chenille++;
              document.getElementById("div1").append(oreen.cat + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
      
            case 1:
              chenille++;
              document.getElementById("div1").append(oreen.dog + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
      
            case 2:
              chenille++;
              document.getElementById("div2").append(oreen.sky + "<br />");
              nieva++;
              updateProgress(chenille, leray.length);
              tvmit_dieUp();
              break;
      
            case 3:
              chenille++;
              document.getElementById("div3").append(oreen.water + "<br />");
              tvmit_liveUp();
              updateProgress(chenille, leray.length);
              break;
          }
      
          OKTY(leray, chenille, aarsh, nieva);
          return true;
      }, 5 * 1000);
      clearTimeout(takeAMoment);
  
      
    } catch (error) {
      console.log(error);
      Swal.fire({
        text: translate("text2"),
        icon: "question",
        buttonsStyling: false,
        confirmButtonText: translate("confirmbtn"),
        allowOutsideClick: false,
        allowEscapeKey: false,
        customClass: {
          confirmButton: "btn btn-primary",
        },
        //refresh again on button click
      }).then(function () {
        location.reload();
      });
    }
  };
  envSoli();

UPDATED WORKING CODE:

const envSoli = async () => {
  try {
    const controller = new AbortController();
    const signal = controller.signal;
    const timeId = setTimeout(() => {
      controller.abort();
    }, 20 * 1000);
    let peticion = await fetch("data.php", {
      method: "POST",
      body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
      headers: { "Content-type": "application/x-www-form-urlencoded" },
      cache: "no-cache",
      signal: signal,
    });
    clearTimeout(timeId);
    let oreen = await peticion.json();

    switch (oreen.enviando) {
      case -1:
        chenille++;
        document.getElementById("div1").append(oreen.cat + "<br />");
        updateProgress(chenille, leray.length);
        tvmit_wrongUp();
        break;

      case 1:
        chenille++;
        document.getElementById("div1").append(oreen.dog + "<br />");
        updateProgress(chenille, leray.length);
        tvmit_wrongUp();
        break;

      case 2:
        chenille++;
        document.getElementById("div2").append(oreen.sky + "<br />");
        nieva++;
        updateProgress(chenille, leray.length);
        tvmit_dieUp();
        break;

      case 3:
        chenille++;
        document.getElementById("div3").append(oreen.water + "<br />");
        tvmit_liveUp();
        updateProgress(chenille, leray.length);
        break;
    }

    OKTY(leray, chenille, aarsh, nieva);
    return true;
  } catch (error) {
    console.log(error);
    Swal.fire({
      text: translate("text2"),
      icon: "question",
      buttonsStyling: false,
      confirmButtonText: translate("confirmbtn"),
      allowOutsideClick: false,
      allowEscapeKey: false,
      customClass: {
        confirmButton: "btn btn-primary",
      },
      //refresh again on button click
    }).then(function () {
      location.reload();
    });
  }
};
envSoli();

Answer №1

The function setTimeout completes immediately without delaying the execution of the following statement. This means that your code effectively cancels the takeAMoment timeout right after setting it.

Since you have already declared a function with async, you should utilize await to introduce a delay in the function's execution.

To simplify the use of await with setTimeout, you can promisify it like this:

// Promisify setTimeout:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

Then, when assigning to takeAMoment, implement it as follows:

        await delay(5 * 1000);
        switch (oreen.enviando) {
            // ...etc
        }

Answer №2

If you're looking to manage a series of updates, consider implementing a queue system. Start by initializing an empty array:

let updateQueue = [];

You can then use the push method to add new updates:

updateQueue.push(newUpdate);

To ensure a smooth flow of updates, you can utilize setInterval along with shift to retrieve one update every 5 seconds:

setInterval(() => {
  let currentUpdate = updateQueue.shift();
  if (currentUpdate) {
    currentUpdate();
  }
}, 5000);

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

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

I am struggling with sending post requests in Node.js

I am currently facing a challenge with handling form data from a webpage using Node.js and writing that data to a file. It seems like there might be an issue with how Node.js is processing my POST request, or perhaps the way I am sending the request from t ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

Incorporating a vanilla JS library (Pickr) into a NuxtJS page component

Recently, I've been experimenting with integrating the Pickr JS library (specifically from this link: [) into my NuxtJS project. To install it, I simply use NPM: npm install @simonwep/pickr In one of my NuxtJS pages - the create.vue page to be exac ...

Retrieve the minimum and maximum values from a multi-dimensional array

If my array consists of the following subarrays: array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] I am looking to determine the maximum and minimum values in this array. For example, in this case: max = 33, min = 0 While I have come across exampl ...

Semantic UI Troubles: Unraveling the Sidebars and #pusher Defects

Hey there, I could really use some assistance with an issue I'm facing. I have this particular structure that's causing me trouble. <div id="toolbar" class="toolbar overlay-displace-top clearfix toolbar-processed"> ... </div> < ...

Suggestions for improving the way time durations are calculated using jQuery

Although I have some experience with jQuery and javascript, I am still relatively new to the world of programming. I can write basic scripts, but I feel that there is room for improvement in optimizing some of my code. Specifically, I'm working on a p ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...

Tips for retrieving the final element from a corrupt JSON string using JavaScript

I've encountered an issue with a nodejs speech recognition API that provides multiple texts in a JSON like structure which renders the data invalid and useless. { "text": "Play" } { "text": "Play astronaut" } ...

Choose an option from the dropdown menu when clicking on the radio button

My issue involves a drop-down menu along with two radio buttons, each with two values: jQuery('input[type=radio][name=radio_type]').change(function(e) { var value = jQuery(e.target.value); jQuery('select[name="optType"] option:selecte ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

"Learn how to handle exceptions in Nest JS when checking for existing users in MongoDB and creating a new user if the user does

Below is the implementation of the addUser method in users.service.ts - // Function to add a single user async addUser(createUserDTO: CreateUserDTO): Promise<User> { const newUser = await this.userModel(createUserDTO); return newUser.save() ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Problems with form functionality in React component using Material UI

Trying to set up a signup form for a web-app and encountering some issues. Using hooks in a function to render the signup page, which is routed from the login page. Currently, everything works fine when returning HTML directly from the function (signup), ...

Setting a value for the identifier just one time

I've been grappling with an issue that's been on my mind for some time now. There are 14 divs on my webpage, and I need each one to be given a random ID (ranging from 1 to 14) every time the page loads. These divs all share the class ".image-box ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Losing $scope reference when incorporating a directive within the controller scope

I have a scenario in my code where I am using two directives. One directive is within the controller scope, while the other directive is not located in the html section. <div ng-show="isStore==true"> <packgroup-directive> ...

Problems Arising with Javascript Animation Functionality

I've created a script for an interactive "reel" that moves up or down when clicking on specific arrow buttons. However, I'm encountering two issues: 1) The up arrow causes it to move downward, while the down arrow moves it upward. 2) After exe ...

Change button to an ajax spinner when it is clicked using jQuery

$(".post-btn").html("<img src='../images/loader.gif' />"); Why isn't this code working? I know I have the correct selector because when I tried $(".post-btn").text('test'), it worked. I want the text of the button to change ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...