0

I have an angular component that needs to cycle through an array. Below, I have an array and a global variable called currentAlbum which will hold the value of the album currently being viewed.

The below works, but with some odd behaviour.

Question 1

Firstly, even though it cycles through correctly, i added console logs to make sure the if statement worked correctly and that it'll begin from the beginning again after reaching the end. The 'currentAlbum' console log will always be one behind of where it appears on screen. Any obvious reason for that? For example, on screen album 3 will be present, the console log will say album 2.

Question 2

I also have 5 buttons on the screen, each one, when clicked will show the selected album. This is a simple this.currentAlbum = selectedValue(selectedValue being received from the HTML click). However, when doing this, the timer continues to run. If the timer is five seconds and I click a carousel button at 4 seconds, the new album will show for 1 second before changing to the next. Is there a way to reset this value? (I've also read that setTimeout is a better approach...?)

  currentAlbum: number = 1;

  albumsArray = [
    { title: "Album 1", index: 1 },
    { title: "Album 2", index: 2 },
    { title: "Album 3", index: 3 },
    { title: "Album 4", index: 4 },
    { title: "Album 5", index: 5 },
  ]

  ---------

  ngOnInit() { 
    this.theCarousel();
  }



  theCarousel() {
    setInterval(() => {
      if (this.albums == 5){
        this.currentAlbum = 1;
        console.log('this is album 5)
      } else {
        this.currentAlbum++;
        console.log('this is not album 5)
      }
    }, 2000);
  }
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Haven
  • 87
  • 1
  • 9

1 Answers1

0

You need to store the interval in a variable or property and then call clearInterval passing into it the variable/property where you stored the interval.

const intervalToClear = setInterval(() => {
      if (this.albums == 5){
        this.currentAlbum = 1;
        console.log('this is album 5)
      } else {
        this.currentAlbum++;
        console.log('this is not album 5)
      }
    }, 2000);
...
clearInterval(intervalToClear);

If you use setTimeout is the same but calling clearTimeout instead.

Eduardo Aboy
  • 151
  • 5
  • Thanks Eduardo! - So this is great at stopping the interval entirely. How would i go about it continuing? Maybe i didn't articulate it well originally. But when clicking one of the buttons, it goes to the right area of the carousel, but doesn't stop for enough time (hence the clear interval...) - However, it doesn't continue after that at the original pace. Anyway to resolve that please? – Haven Jul 13 '20 at 08:52
  • If you want to continue you'll need to create a new setInterval or setTimeout, you cannot pause and continue it, you need a new one. – Eduardo Aboy Jul 14 '20 at 09:18