Search code examples
javascriptvue.jstimer

Idle timer within Vue Component


I am have some issues resetting my timer when no longer idle. I am using Vue Idle for this, which is a wrapper for idle.js.

So I have a modal with the id timeout-modal. When Vue Idle triggers the idle function, I call showWarningMessage.

Within this function, I first display my modal. I then create a timer which my modal uses to do a countdown. So this all works fine.

<script>
    export default {
        data() {
            return {
                timerId: 0,
                remainingTimeoutSeconds: 10000
            }
        },
        computed: {
            second() {
                return this.remainingTimeoutSeconds / 1000;
            }
        },
        onIdle () {
            this.showWarningMessage();
        },
        methods: {
            showWarningMessage() {
                this.$bvModal.show('timeout-modal');
                this.warning = true;

                 this.timerId = setInterval(() => {
                    this.remainingTimeoutSeconds -= 1000;
                }, 1000);
            },
        }
    }
</script>

Now within the modal there is a continue button. When pressed, it should basically reset the above timer. At the moment I have

handleContinueButtonClick(response) {
    if (response.data.success) {
        console.log("IN")
        this.$bvModal.hide('app-timeout-reminder-modal');
        clearInterval(this.timerId);
        return;
    }
}

So what this should do is hide the modal, and then reset the timer back to 10 seconds. It is entering the above as the console is printing IN. The modal is also hidden when I click OK.

However, the next time the modal is displayed, the timer is already near 0 as it did not reset back to 10.

Is there any reason why I cant get this back to 10 seconds? I thought clearInterval should reset the timer?

Thanks


Solution

  • I thought clearInterval should reset the timer?

    Do you mean this.remainingTimeoutSeconds is set automatically when calling clearInterval?

    The answer is no.

    You need to reset that value as 10000 like blow;

    handleContinueButtonClick(response) {
      if (response.data.success) {
          console.log("IN")
          this.$bvModal.hide('app-timeout-reminder-modal');
          this.remainingTimeoutSeconds = 10000;
          clearInterval(this.timerId);
          return;
      }
    }
    

    or

    showWarningMessage() {
      this.$bvModal.show('timeout-modal');
      this.warning = true;
      this.remainingTimeoutSeconds = 10000;
    
      this.timerId = setInterval(() => {
        this.remainingTimeoutSeconds -= 1000;
      }, 1000);
    }