Home > Software engineering >  How to loop through an array indefinitely and display the value in Angular?
How to loop through an array indefinitely and display the value in Angular?

Time:04-26

I have an array of words and my goal is to display each one of them in an HTML template every few seconds. The result should be something like this: https://bootstrapmade.com/demo/iPortfolio/

I know it is possible to do so by using the following JavaScript Code:

  const typed = select('.typed')
  if (typed) {
    let typed_strings = typed.getAttribute('data-typed-items')
    typed_strings = typed_strings.split(',')
    new Typed('.typed', {
      strings: typed_strings,
      loop: true,
      typeSpeed: 100,
      backSpeed: 50,
      backDelay: 2000
    });
  }

I tried to replicate the same effect using typescript and I wrote the following code instead:

export class HeroComponent implements OnInit {

  words: string[] = ['marco', 'polo'];
  word: string = "";
  constructor() { }

  ngOnInit(): void {
    setTimeout(() => {
    while(true){
      for (let i=0; i < this.words.length; i  ) {
        setTimeout(() => {
        this.word = this.words[i];
        console.log(this.word)
      }, 4000)
      };
    }}, 4000);
  }
}

However once I run the website it says that it runs out of memory.

Would you be able to suggest a smart and elegant way to achieve the effect linked in the website above?

CodePudding user response:

Remove the use of the for, while loop, and setTimeout

Use a plain JavaScript setInterval, or since you're using Angular, an RxJS interval. Keep track of an index value (a number), use it to access the array values (words[index]), and increment the index on each execution of the interval

You can also add an if guard to check if array length exceeded - and cancel the interval if so

CodePudding user response:

words: string[] = ['marco', 'polo'];
word = new Subject<string>();
ngOnInit(): void {
  for (let i = 0; i < this.words.length; i  ) {
    SetTimeout(() => this.word.next(this.words[i]), 4000)
  }
}
  • Related