Search code examples
javascriptrefreshsettimeout

How to Overwrite or Refresh javascript setTimeout


I need to refresh or overwrite setTimeout delay value.. I have a product quantity update button:

<q-input class="q-pb-none" v-model="quantity" dense borderless style="width: 25px" mask="###" @input="updateQty" />
<div class="col-auto">
          <div class="row"><q-icon name="keyboard_arrow_up" @click="quantity++" class="cursor-pointer"/></div>
          <div class="row"><q-icon name="keyboard_arrow_down" @click="quantity--" class="cursor-pointer"/></div>
        </div>

I don't want to make update request on every clicking of qty change buttons, instead of this following updateQty function should run 3 seconds later then user give up to click the button.

updateQty () {
// I need to refresh this timeout at evertime this function called.
      window.setTimeout(() => {
        this.$store.dispatch('pack/updateProductQty')
      }, 3000)
    }

How can I set this logic? I use quasar vue.js framework. Thank you..


Solution

  • You can set the timeout id into a variable and clear the timeout on each click:

    let timeoutId;
    
    updateQty () {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        timeoutId = window.setTimeout(() => {
            this.$store.dispatch('pack/updateProductQty')
        }, 3000)
    }
    

    IMHO a cleaner solution would be using Observables or similar technique.