Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind:

function fetchDesign (items) {
  items.map(item => item.classList.add('selected'))
  // additional code here
}

Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensuring that the rest of the code runs synchronously after all iterations are completed?

(Just to clarify, 'items' is an array containing HTML elements)

UPDATE: Here's what I've attempted so far:

items.forEach(item => setTimeout(() => { item.classList.add('selected') }, 2000))
items.map(item => setTimeout(() => { item.classList.add('selected') }, 2000))

setTimeout(() => {
 items.map(item => item.classList.add('selected'))
}, 2000)
setInterval(() => {
 items.map(item => item.classList.add('selected'))
}, 2000)

My current struggle includes encountering the exact issues I set out not to face initially: addClass does not get delayed as required and all iterations happen simultaneously. Furthermore, the following lines of code run asynchronously, causing immediate display of console.log outputs.

Answer №1

Utilizing Promises allows for the sequential addition of classes to each DOM node, as well as executing code once all nodes have been processed.

var myArrayOfDomNodes = Array.from(document.querySelectorAll('p'));

addClassesWithDelay(myArrayOfDomNodes).then(_ => {
    // this block of code will execute after all classes have been added.
    console.log('process complete');
});

function addClassWithInterval(node) {
    return new Promise(res => {
        setTimeout(_ => {
            node.classList.add('highlighted');
            res();
        }, 2000);
    });
}

function addClassesWithDelay(sequence) {
    let item = sequence.shift();
    return item ? addClassWithInterval(item).then(addClassesWithDelay.bind(null, sequence)) : Promise.resolve();
}
p.highlighted {
  background-color: yellow;
}
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>

Answer №2

If you need to temporarily stop the execution of your script, using setTimeout or setInterval is the way to go. However, since all setTimeout calls will run simultaneously, you'll have to either nest them or set increasing timeouts (e.g. 2s, 4s, 6s, ...). To achieve the latter, you can use the following code snippet:

`sequence.forEach((item, index) => setTimeout(() => { item.classList.add('active') }, (index + 1) * 2000))`

To ensure that the rest of the script runs after all callbacks have finished, wrap it in a final setTimeout with a delay of sequence.length * 2000 (or (sequence.length + 1) * 2000, depending on your requirements).

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

Utilizing a Meteor Method within a Promise Handler [Halting without Throwing an Error]

I've been working on integrating the Gumroad-API NPM package into my Meteor app, but I've run into some server-side issues. Specifically, when attempting to make a Meteor method call or insert data into a collection within a Promise callback. Be ...

Understanding the contrast between a put request subscription with an arrow versus without in Typescript

I'm sorry if the title is not very clear. In my Angular project, I have come across two different put requests: public Save() { const types: string[] = this.getTypes.getCurrentTypes(); this.userTypeService .updateTypes(this.userID, gro ...

Guide on utilizing Redux's Provider in React applications

I have been diving into the world of ReduxJS by closely following the documentation provided here. Towards the end of the document, it talks about utilizing the provider object. I have taken the step to wrap my App component in the provider as shown below ...

Inheritance of nested directives in Angular.js

Click here for a live example I'm trying to understand how 00B can be contained within 00A. Here is the code snippet: <div directive-one="['foo', 'bar']"> <directive-two /> </div> In this code, the directi ...

What are the steps to install the LTS release of NodeJS if Node 10 is already installed on my system?

Several weeks ago, I installed Node version 10.11 on my computer. However, a repository I am working with requires me to have the LTS version of Node, which is currently 8.12. If I download the LTS version, will it interfere with my existing install, or ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...

Obtain a 404 rendering using EJS in an ExpressJS application

Utilizing express ejs on both my backend and frontend, I have set up a route to display the dashboard on the admin page. However, when attempting to access my URL http://localhost:3000/admin, I am encountering a 404 error when trying to render the view. He ...

Transferring checkbox data to Bootstrap modals and dynamically summoning specific div modals using their unique identifiers

I have been trying to populate the checkbox values into corresponding modal divs based on button clicks, but I am facing difficulties in achieving it. Desired outcome: The buttons should trigger the display of selected checkbox values in their respective ...

Eliminate the presence of core-js in the nextjs bundle

Currently, I am tackling the challenge of minimizing bundle sizes in my Next.js project. One particular aspect that caught my attention is the inclusion of a core-js bundle for polyfills. This adds an extra 50KB to the size of the main bundle, which I aim ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

What steps should I take to display a Material UI grid in React without triggering the warning about the missing unique key

In my current project, I am utilizing React and Material UI to display a grid. The grid's rows are populated from an array of data, with each row containing specific information in columns structured like this: <Grid container> {myData.map((re ...

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

React components do not re-render when the context value changes

The issue with React not re-rendering when the context value changes persists I am using tailwindcss, React(v18.2.0), and vite(3.2.4). I have already attempted i want that clicking on TodoItem should change the completed value in the todo using React con ...

Finding the location of PIE.htc in the Firebug tool

After encountering issues with CSS3 properties not working on IE 7 and IE 8, I decided to include PIE.HTC. Visit this link for more information Upon viewing the page in IE, I realized that the CSS3 properties were not being applied as expected. I attempt ...

The Click Event Is Triggering Even with Correct Callbacks Being Set

I am struggling to understand why these functions are not executing properly. I know the correct syntax for binding a function, like this: $('#idOfThing').bind('click', foofunc); function foofunc() { ///do things } However, I am facin ...

Encountering a problem while verifying pattern using regular expressions

I'm facing an issue when manually checking if my inputs match the specified patterns. Below is the function I am using for this check: if (!$element.attr("pattern")) return true; let pattern = $element.attr("pattern"); le ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

Customizing line charts with D3.js and AngularJS for ultimate visual impact

Working on a project involving the creation of a line chart using D3.js library and AngularJS within an Ionic framework. I am looking to customize the color of data points based on the Y-axis values. For example, if the value falls between 0-30, I want t ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...

Access to Web Share API requires permission

I am currently attempting to integrate the Web Share API feature into my testing web application, but unfortunately, I seem to be encountering some difficulties. Below is the code snippet I have been working with: const newVariable: any = navigator; {newV ...