0

I have currently assigned a setTimeout function to a Vue method and I want to use clearTimeout for this function. Is that possible? If so, how can I do this?

    methods: {
        timeoutController() {
          setTimeout(function() {
            this.controllerShown = false;
          }, 3000);
        }
....
2
  • 1
    You should follow your consideration of using a method instead. Commented Mar 20, 2020 at 8:01
  • @AEB yes, you can store the id of the timeout in Vue data property & clearTimeout with that id in an another fn as answered below. Commented Mar 20, 2020 at 9:33

2 Answers 2

3

new Vue({
  el: '#app',
  
  data: {
    timer: null
  },
  
  methods: {
    startTimer () {
      this.timer = setTimeout(() => {
        console.log("execute me")
      }, 3000)
    },
    // If you kill the timer before setTimeout callback has been executed the callback wont get executed
    killTimer () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="startTimer()">start</button>
  <button @click="killTimer()">kill</button>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Why do you need to assign a function to a Vue component's data?

setTimeout() will execute the function 3000 ms later and give the timer to this.timeout. The timer will never execute again, no matter where you assign to.

1 Comment

there are scenarios where it's required to clear the setTimeout before it has done executing the callback function, eg. we often clear timeouts in debounce

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.