Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds.

My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else.

I'm struggling to find a solution.

export class MessagesComponent implements OnInit {
      items = ['test 01', 'test 02', 'test 03'];
      currentItem: any;
      private interval;

      constructor() {}

      ngOnInit() {
        for (let i = 0; i < this.items.length; i++) {
          this.interval = setInterval(() => {
            this.currentItem = this.items[i];
          }, 3000);
        }
      }
    }
{{ currentItem }}

Any assistance would be greatly appreciated!

Answer №1

Consider implementing it in a slightly different manner.

The variable pointer is utilized to track the current content for display. It increments by 1 at each interval until reaching a value greater than 2, after which it resets to 0.

export class MessagesComponent implements OnInit {
  items = ['example 01', 'example 02', 'example 03'];
  currentItem: any;
  private pointer: number = 0;

  constructor() {}

  ngOnInit() {
      this.interval = setInterval(() => {
        this.currentItem = this.items[this.pointer];
        this.pointer++;
        if (this.pointer > 2) { this.pointer = 0 };
      }, 3000);
  }
}

Answer №2

Give this a shot:

export class MessagesComponent implements OnInit {
  words = ['example 01', 'example 02', 'example 03'];
  currentWord: any;
  private timer;

  constructor() {}

  ngOnInit() {
    for (let i = 0; i < this.words.length; i++) {
      this.timer = setInterval(() => {
        this.currentWord = this.words[i];
      }, 3000 * i);
    }
  }
}
{{ currentWord }}

Answer №3

If you're enjoying the functionality of rxjs,

import { timer } from 'rxjs';
import { tap } from 'rxjs/operators';

ngOnInit() {
  timer(0, 3000)
    .pipe(
      tap(v => {
        this.currentItem = this.items[v%3]
      })
    )
    .subscribe(console.log);
}

With less code and no need for loops or intricate logic involved :)

You can take it a step further with

export class MessagesComponent implements OnInit {
  private timer$ = timer(0, 3000);
  ngOnInit() {
    // The for loop can be completely eliminated
  } 
}

In your html, simply use

{{ items[(timer$ | async) % 3] }}

By utilizing the async pipe and rxjs, you can achieve the same goal with just one line of code and ditch the messy for-loop.

Check out a demo here

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

Having trouble retrieving data from the server for the POST request

I am fairly new to using Jquery and Ajax requests. I'm currently working on a website where I have a simple form that collects an email address from users and sends it to the server. However, I'm struggling to figure out how to capture the form d ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Various input tools available for every Textarea

I'm grappling with this particular case. Each textarea should have its own toolbox, but currently only one is active (I anticipate having more than 2 areas, so JavaScript needs to be able to recognize them by ID) I attempted to use something like: f ...

Creating a user-friendly interface for an array of objects, complete with an included array containing those same objects

I have an array that I want to iterate through. It contains a single object and an array of objects. How can I create an interface for this structure? What is the appropriate declaration to replace any[]? Here is the code: export const initialPhotoProps: ...

Can CSS be used to create curved dashed lines?

Is it possible to achieve dashed lines similar to the ones highlighted in the images below using only CSS? I have a responsive web page built with Bootstrap, and I need the dashed lines to adjust accordingly when the window width changes. ...

Implementing the React Router into a ReactJS project: Methods to prevent users from clicking on links within React-Router's <Link> component

I'm exploring React-Router's Link and have set up the following: <Link to={...}>{this.props.live? "Live": "Not Live"}</Link> In this configuration, if this.props.live is present, I want to display the text "Live" which will lead to ...

Executing multiple instances of the cascading dropdown fill method in Angular 7

I am currently working on an Angular app that includes cascading comboboxes for country and state selection. However, I have noticed that the get states() method in my state.component.ts file is taking a long time to run. What could be causing this issue? ...

How can I use JavaScript to create a drop-down menu that only appears after selecting the previous one?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id=" ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

Making a POST request across domains without relying on any third-party frameworks

Is it possible to create a cross-domain request using vanilla JavaScript without relying on frameworks like jQuery? I am looking to send a JSON to a service on a different domain and receive the response using a callback function. Can this be done solely ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

What is the correct way to specify the data type for the useState hook when I intend to store an array of objects?

My dilemma involves storing an array of objects using the useState hook, but I am struggling with the syntax required to describe the expected type. The type that I want to store is Array<Updates>. Below is the code I have: const [messages, setMessa ...

Develop a function for locating a web element through XPath using JavaScriptExecutor

I have been working on developing a method in Java Script to find web elements using XPath as the locator strategy. I am seeking assistance in completing the code, the snippet of which is provided below: path = //input[@id='image'] def getElem ...

Issue with Ajax not triggering PHP script

My first experience with using Ajax to call a php script is not going well. The script doesn't seem to be working at all. Here is the snippet of code where I implemented Ajax: <?php if (isset($_GET['error'])) { switch ($_GET[ ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

Is there a method available to incorporate a scroller into an nvd3 chart?

I am encountering an issue with my nvd3 chart. When I have a large amount of data that exceeds the width of the chart container, there is no scroll bar present and I'm struggling to figure out how to add one. I attempted to include overflow:scroll wi ...

Form submission resulting in 405 error

Currently, I am facing an issue while trying to send data to the server. The PHP side seems to be functioning correctly as the post request is successful when tested using Postman. However, when attempting to do so from Angular, I encounter a 405 (Method N ...

Can you eliminate data errors within a Vue component?

In my Vue instance, I will be making a multitude of API calls to modify various variables. The initial value of these variables is not crucial. I had hoped there might be a way to avoid defining them upon the creation of the vm, but this approach doesn&ap ...

What is the best way to integrate ContextualMenu with Persona in Office Fabric UI React?

Currently, I am utilizing Office Fabric UI React to work on a project. My goal is to implement a ContextualMenu in conjunction with the Persona object. In this particular example, I am demonstrating how ContextualMenu can be applied directly to differ ...

Testing an Angular directive that includes a form unit test

In my directive, I have implemented a form property which is applied to a submit button. The directive listens for click events on the submit button and validates the form when clicked. If the form is not valid, the directive prevents the click event from ...