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

User controls in ASP.NET may not trigger the jQuery (document).ready() function

I wrote a jQuery function within my ASP.net user control that is not functioning as expected: <head> <title></title> <script src="~/Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script language="javascript" ty ...

Sending postMessage during the beforeunload event does not work as expected

When postMessage() is triggered within the beforeunload window event in an Ionic 2 browser, I've noticed that the message doesn't make it to the parent. However, if the same message is sent during the unload or load event, it is received successf ...

Parsing JSON into a List of Objects

Here is a filter string in the following format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I am looking to deserialize this into a Generic list of items. Any tips on how I can accomplish this? ...

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

conceal specific language options within the dropdown selection box

In my user interface, I have implemented a drop-down menu that allows users to select their preferred language. I want the selected language option to disappear from the drop-down menu once chosen. Here is the HTML code snippet: <li> < ...

What is the best way to deactivate unclicked href links within a loop?

Looking at the template image, my goal is to disable all links that were not clicked when one of the links from 'number1' to 'number3' is clicked. For example, if 'number2' is clicked, then 'number1' and 'number ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Bot in discord.js refuses to exit voice channel

I've been struggling to get my bot to leave the voice channel despite trying multiple methods. Here's what I've attempted in the source code: Discord.VoiceConnection.disconnect(); Although this is the current code, I have also tested: messa ...

Creating a video that plays frame-by-frame on an HTML5 canvas and can be controlled with a slider

I am currently working on a walkthrough video where the user has the ability to slide a UI slider across the screen, causing the camera to navigate through a 3D space. The video itself has been exported in jpg frames, numbered from 0 to 350.jpg. My appro ...

Utilizing the Vuex/Redux store pattern to efficiently share a centralized source of data between parent and child components, allowing for customizable variations of the data as

Understanding the advantages of utilizing a store pattern and establishing a single source of truth for data shared across components in an application is essential. Making API calls in a store action that can be called by components, rather than making se ...

Sharing models between AngularJS controllers

I am currently in the process of developing an application that will showcase various charts and controls to filter the presented data. I have structured the HTML page in a way that remains consistent throughout, leading me to consider creating an HTML tem ...

Showing C# File Content in JavaScript - A Step-by-Step Guide

Is there a way to showcase this File (c#) on a JavaScript site? return File(streams.First(), "application/octet-stream", Path.GetFileName(element.Path)); I am looking for something similar to this: <img id="myImg" src="_____&qu ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

How to remove the black border on a material-ui button

I am currently working with the material-ui datepicker and buttons. Whenever I click on the datepicker icon to select a date or any of the buttons, I notice a black border appearing. How can I remove this black border from the design? ...

arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields. Here is an example snippet of the JSON data: { "Racename": "10KM", "Category": 34, "Gender": "Male", "Work": "Google", "FullName": "Dave Happner", "Rank": 1, "Poni ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...