Brian
Brian

Reputation: 27

clear interval on another function vue js

I'm confused how to add a set Interval variable in my vue file myTimer = setInterval(function, time). The goal of my program is to change the number variable every 3 seconds, to access the object that I created to let it display different background images but I also have 2 buttons that can navigate through the background as well.

This is my template code

<div class="background" :style="{backgroundImage: `url(${Images[`${number}`].picture})`}">
   <div class="content_container">
      <div v-on:click="prev" class="prevButton"><p>&lt;</p></div>
         <div class="title_container">
            <div class="theTitle"><p>{{Images[`${number}`].Title}}</p></div>
         </div>
      <div v-on:click="next" class="nextButton"><p>&gt;</p></div>   
   </div>
</div>

This is my set Interval code

export default {
  data: () => ({
     number: 0,
     myTimer     
  }),
  mounted:function() {
    this.$nextTick(() => {
      this.timer();
    });
  },
  methods:{ 
    timer: function() {
      var myTimer = setInterval(this.counter, 3000);
  },
  counter:function(){
     if(this.number >= (this.Images.length -1)){
        this.number = 0;
     }
     else{
        this.number +=1;
     }
     },
     next()
     {
        clearInterval(this.myTimer)      
        if(this.number >= (this.Images.length -1)){
           this.number = 0;
         }
        else{
           this.number +=1;
         }
     },

I want to clearInterval at the next() function how can I access the variable from another function.

Upvotes: 0

Views: 455

Answers (1)

wenzi
wenzi

Reputation: 388

your myTimer need be in this context.

export default {
  data: () => ({
    number: 0,
    myTimer: 0, // init myTimer
  }),
  mounted: function () {
    this.$nextTick(() => {
      this.timer();
    });
  },
  methods: {
    timer: function () {
      this.myTimer = setInterval(this.counter, 3000); // in this.myTimer
    },
    counter: function () {
      if (this.number >= this.Images.length - 1) {
        this.number = 0;
      } else {
        this.number += 1;
      }
    },
    next() {
      clearInterval(this.myTimer); // clear
      if (this.number >= this.Images.length - 1) {
        this.number = 0;
      } else {
        this.number += 1;
      }
      this.timer(); // start next
    },
  },
};

Upvotes: 1

Related Questions