Tips for adding a delay in between iterations of a for-loop

I'm working on a project where I need to display a series of slides, each with a specified display duration. My idea is to store these slides in an array and loop through them, showing each slide for the correct amount of time before moving on to the next one.

Here's my approach:

for (let  i= 0; i < this.slides.length; i++) {
  setTimeout(() => {
    this.currentSlide = this.slides[i]
  }, this.slides[i].slidetime * 1000);
}

I even experimented with this alternative method:

for (let  i= 0; i < this.slides.length; i++) {
  this.currentSlide = this.slides[i];
  this.wait(this.slides[i].slidetime);
}

wait(seconds) {
  setTimeout(() => {}, seconds * 1000);
}

Unfortunately, neither of these approaches worked as expected.

Answer №1

To handle this situation, you can leverage the angular tag and work with Observables:

from(this.slides).pipe(
  concatMap((slide) => of(slide).pipe(
    tap((slide) => this.currentSlide = slide),
    delay(slide.slideTime)
  ))
).subscribe()

If dealing with observables seems complex, an alternative method is to use await/async:

async goThroughSlides(): Promise<void> {
  for (let i = 0; i < this.slides.length; i++) {
    this.currentSlide = this.slides[i];
    await new Promise((resolve) => setTimeout(resolve, this.currentSlide.slideTime));
  }
}

For easy reference, I have provided a working example on stackblitz

Answer №2

Declare a new variable to store the slide values and incorporate it into your HTML structure.

updateSlides: any;

for(let index = 0; index < this.slides.length; index++){
        let currentSlide = this.slides[index];
        setTimeout(() => {
            this.updateSlides.push(currentSlide);
        }, 2000*(index+1));
    }

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

How can I customize the appearance of the file input button in Angular Material?

Despite browsing numerous similar questions, I have yet to find a solution to my issue. My setup includes Angular 11, Angular Material 8, and a file input structured like this: <div class="form-group"> <input #myInput type="fil ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference. Component ngOnInit() { this.getCurrentLocation(); } getCurrentL ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Mastering Angular 7: A guide to efficiently binding values to radio buttons

Struggling to incorporate radio buttons into my project, I encountered an issue where the first radio button couldn't be checked programmatically. Despite attempting the suggested Solution, it didn't resolve the problem within my code. Below is ...

RXJS Subject data remains stale upon page refresh

A specific service I developed includes a subject titled selectedNode. My goal is to update the subject's value when providing a direct URL for page loading. Unfortunately, there seems to be an issue with updating the value of Subject directly via the ...

Create an Angular directive input using backticks to input AsciiMath code which can be rendered using MathJ

I recently implemented MathJax in my Angular app following this guide: here. I was successful in getting it to work with asciimath format. However, I encountered an issue when trying to input a literal value into the field. When it's working: app.ts ...

`Changing environment variables in Angular during execution`

I am looking for a way to dynamically change the URL that my Angular application fetches resources from during build time. I want to be able to pass a parameter while building in order to modify the URL value, particularly for deployment in different Docke ...

Obtain the property for a shared component using React and TypeScript

How can typescript be informed about the err type? type InputProps = { err?: boolean } export const Input = forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<'input'>>(({ err, ...rest }, ref) => { // code that uses ...

Issues are arising with Angular Form where the FormControl is not being properly set up for the first field in my form

After grappling with this issue for several weeks, I am still unable to pinpoint the cause. (Angular version: 16.1.4) The form component is populated using a BehaviorSubject, and although the console prints out the correct values for both the form and dat ...

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

Tips for utilizing dispatch within a client class?

As I continue my journey of developing a client/wrapper using axios with Zod and Redux, I aim to create a client that can handle fetch errors and dispatch necessary state updates to Redux. After successfully implementing Zod and the validation part into t ...

Unable to organize list of entities based on numerical values

I am working with an array of objects structured like this: [ { "value": 351.68474, "o_p": [ "$.text" ] }, { "value": 348.0095, "o_p": [ ...

How do you properly include a new property in an Object using Typescript?

I am currently delving into the world of typescript. After exploring various sources like this one and that one, as well as trying out multiple solutions, I have encountered a challenge. I have a variable named incomingArticleObject which needs to be of ty ...

`Database Schema Enforcement in Firestore: Custom Objects vs Security Rules`

Firestore, being a noSQL database, is schemaless. However, I want to ensure that the correct data type is being passed in. Custom Objects As per Firebase documentation, https://firebase.google.com/docs/firestore/manage-data/add-data class City { const ...

Ways to automatically select a radio button in Angular without using NgModel

I have been reviewing all the questions here and came across one about selecting a radio button by default without using ngModel. <input type="radio" formControlName="calculate" value="1"> <input type="radio" ...

Enhance the appearance of data in Angular using a pipe or alternative method

Currently in my Angular 8 application, I have some data displaying in a div like so: {"Information":"Information one","Output":[{"address1":"someaddress"},{"address2":"someaddress"},{"address3":"someaddress"},{"address4":"someaddress"}]} However, it&apos ...

Can you explain the meaning of `((prevState: null) => null) | null`?

Upon encountering this code snippet: import { useState } from "preact/hooks"; export default function Test() { const [state, setState] = useState(null); setState('string'); } An error is thrown: Argument of type 'string' ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...