Reputation: 807
I'm trying to use the setInterval()
function in order to change text to the user every 3 seconds.
I tried looping with for loop but that doesn't work - I see the 'test 03' and that's it.
I can't 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 }}
Appreciate any help!
Upvotes: 1
Views: 2004
Reputation: 3823
If you are happy with 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);
}
less code, no loop, no fancy logic involved :)
You can do even better with
export class MessagesComponent implements OnInit {
private timer$ = timer(0, 3000);
ngOnInit() {
// for loop can be completely removed
}
}
and in html, use
{{ items[(timer$ | async) % 3] }}
so you literally just use 1 line of code to do the same thing by leveraging async pipe and rxjs, and forget about the ugly for-loop.
demo https://stackblitz.com/edit/angular-m5prrk?file=src%2Fapp%2Fapp.component.ts
Upvotes: 1
Reputation: 31815
Try this:
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 * i);
}
}
}
{{ currentItem }}
Upvotes: 1
Reputation:
Try it this way instead.
pointer
points to the current content you want to display. With each interval pointer gets increased by 1 until it has a value > 2. Then it starts with 0 again.
export class MessagesComponent implements OnInit {
items = ['test 01', 'test 02', 'test 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);
}
}
Upvotes: 3