undefinedfix
Sign in

Vue how to stop the timer in another method?

PaulELI edited in Sat, 08 Oct 2022

Two buttons trigger start and stop events respectively. What should I do if I want to stop the timer in stop?

start () {
  let timer = setInterval(() => {
  }, 5000)
},
stop () {
}
3 Replies
anlar
commented on Sat, 08 Oct 2022
<script>
export default {
  data() {
    return {
      timer: null
    }
  },
  methods: {
    start() {
      this.timer = setInterval(() => {}, 5000)
    },
    stop() {
      clearInterval(this.timer)
    }
  }
}
</script>
Braden
commented on Sat, 08 Oct 2022

Let timer is changed to this.timer

griloHBG
commented on Sat, 08 Oct 2022

Raise timer to a global variable and use this.timer