Using setTimeout within a ForEach loop does not adhere to the specified milliseconds for waiting

Although ForEach console.log's very fast, I am looking to introduce a delay of 8 seconds before logging the next item in Set. I experimented with setTimeout but it doesn't appear to output at the precise milliseconds specified.

const completedIds = [];

//Dom mutation observer
const observeChat = new MutationObserver(function(mutationsList) {
  for (let mutation of mutationsList) {
    if (mutation.addedNodes.length) {


      for (i = 0; i < mutation.addedNodes.length; i++) {
mutation.addedNodes[i].firstChild.naturalWidth < 51 ? pm(mutation.addedNodes[i].firstChild.src.slice(-48, -12)) : false
      }
      
    }
  }
});
observeChat.observe(document.querySelector('.accounts-container__list'), {attributes: true, childList: true, subtree: false});

// Pm function
pm = ids => {
  observeChat.disconnect();
  if (!completedIds.includes(ids)) {
    const img = new Set().add(ids).forEach(function(id, index) {
      setTimeout(function() { // This is not functioning as expected. It does NOT log in the console every 8 seconds
        console.log(id)
      }, index * 8000)
    })
  }
  observeChat.observe(document.querySelector('.accounts-container__list'), {attributes: true, childList: true, subtree: false});
}

Answer №1

Here are a few issues to address.

  1. When creating a Set, remember that the entries do not spread out automatically. Adding an array to a set results in just that array being stored. It seems like you intended to spread it out instead.

  2. The values in a set serve as its indexes, unlike the index provided by the forEach method for arrays. Multiplying the ID you added by 8000 may lead to unexpected results.

  3. The variable img will always be undefined since the return value of Set.prototype.forEach is undefined.

If your goal is to obtain unique values using Set, consider the following steps:

  1. Create the set using new Set(...ids),

  2. Convert it back to an array before using forEach,

  3. Find another way to initialize the variable img. Its intended purpose is unclear at this point...

You can implement the suggested changes in the code snippet below:

    [...new Set(ids)].forEach(function(id, index) {
//  ^^^^−−−−−−−^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− here
        setTimeout(function() {
            console.log(id);
        }, index * 8000);
    });

See the live example above for reference.

In addition, you have the option to use a for-of loop with a counter:

let index = 0;
for (const id of [...new Set(ids)]) {
    setTimeout(function() {
        console.log(id);
    }, index++ * 8000);
}

Refer to the second live example for demonstration purposes.

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

What steps do I need to follow in order to incorporate and utilize an npm package within my Astro component

I have been working on integrating KeenSlider into my project by installing it from npm. However, I am encountering an error message that says Uncaught ReferenceError: KeenSlider is not defined whenever I try to use the package in my Astro component. Belo ...

What are the steps to enable a Vue component to handle its own transitions?

I am looking for a way to handle enter and leave animations in Vue when components are mounted or removed. My goal is to consolidate all the animation code into its own component for better organization. <template> <transition @enter="enter" ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

The lack of definition for the props value poses an issue in React.js Hooks

I'm currently developing a notepad web application that utilizes React Hooks for managing state variables. In order to fetch data from an API, I am using the axios library. The retrieved data consists of objects with fields such as _id, title, status, ...

Error in VueJS when attempting to call a method within a v-for loop: 'not defined on the instance but referenced during render'

I’m still getting the hang of Vue.js (Vuebie?), and while I know this question has been asked before, I’ve not quite stumbled upon a solution myself. My current challenge involves passing an object to a method in order to increment a value and then di ...

Incorporating JavaScript/jQuery values into C# backend with ASP.NET

Despite attempting all possible methods, I am unable to pass the screen.width value from a JS script on an aspx page to C# in the code behind. Even though the screen.width is correctly assigned, it never gets passed to my hidden field value. <asp:Conte ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

The unexpected token "[ ]" was encountered while assigning a numerical value to an array

Hey everyone, I have a question that's been bothering me and I can't seem to find the answer anywhere. I'm currently learning pure JavaScript and although I am familiar with several other programming languages, I keep running into an issue ...

How can I refresh the information without appending it to the existing table using JavaScript and jQuery?

I am currently utilizing the pusher API and I am facing an issue where the data gets added to my table every time a new state is called. Instead, I want to update the existing data in the table without creating a new row every time. I only want to add a ne ...

Trying to add a single value to a specific index in a JavaScript array, but it is mistakenly assigning multiple values at once

Currently tackling a matrix algorithm with an early roadblock. The array at hand is: [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] The goal is to convert it into this: [ [ 0, 0, 0 ], [ 0, 9, 0 ], [ 0, 0, 0 ] ] My plan was to alter the middle value like so ...

Choosing an ID along with a numerical value in jQuery

Being new to both stackoverflow and jQuery, I'm facing a challenge in creating a basic function. In my website, there are multiple links with IDs such as "filtro1", "filtro2", and so on. My goal is to write a single piece of code that will be trigger ...

Is there a more efficient method for configuring mongo?

I'm dealing with a set of documents that are identical but can be categorized into two distinct groups based on their usage patterns. One group, referred to as "current", consists of a small number of documents that are queried frequently. The other ...

A sophisticated approach to implementing a search functionality within a complex JSON structure containing nested arrays using JavaScript

Searching for data in JSON format: { "results": { "key1": [ { "step": "step1", "result": "pass" } , { "step": "step2", "result": "pending" } ...

Ext JS - A grid cell containing varying values, accompanied by a selection of combo boxes

I'm currently implementing the Ext JS Grid component and have a list of fields with their respective data types: ID (int) Name (string) Foods (List<string>) Each user can have multiple foods, selected from a Food DataStore. Displaying this in ...

Transmit an HTML table to PHP

I have successfully created a dynamic table within a form, but for some reason, it's the only element that is not being fetched. To build this table, I utilized the bootstable framework which allows for easy creation of tables with interactive featur ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Issue with passing multiple promises to $q.all function

Currently, I am attempting to iterate through an object and fetch data for each iteration from two separate service API functions. These functions return promises due to using the $http object, which means I must wait for the responses before populating my ...

What is the process of converting the string 'dd/mm/yy hh:MM:ss' into a Date format using javascript?

I successfully completed this task. var date = 'dd/mm/yy hh:MM:ss'; var dateArray = date.split(" "); var splitDate = dateArray[0].split("/"); var splitTime = dateArray[1].split(":"); var day = splitDate[0]; var month = sp ...

Using AJAX and PHP to dynamically fill HTML drop-down menus

In order to populate the DropDown controls on my HTML Form dynamically, I have implemented a code that utilizes AJAX to make a call to a .php file. This .php file is responsible for filling the DropDown control with values from a single column. Throughout ...