javascriptvue.jssettimeoutcleartimeout

How to reset a setTimeout if you receive data while time is running?


I have in my VUE application a text type input in which I collect a data and when I finish collecting it I must show another component.

                <input
                type="text"
                v-model="textFormInfo.text"
                @keypress="onChangeText($event)"
                />
                <div class="loader-spinner" v-if="loading">
                  <app-loader ref="spinner"/>
                </div>


and this is the method in which I control the interaction. I'm detecting through the keypress when they start typing in the input and when there is .length I launch a settimeout to give time for them to type and display a loader and load the next component.

export default {
  data() {
    return {
      myTimeout: null
    };
  },



    onChangeName(event) {
      if (event.target._value.length > 0) {
        this.loading = true;
        this.myTimeout = setTimeout(() => (
          this.isNameCompleted = true, 
          this.loading = false,
          this.isLoaderFinished = true,
          this.$refs.scrolled_3.focus()), 2200);
      }
    }

the problem is that if you type slowly or the information is too long the next component is displayed before you have finished typing. I'm trying to make sure that every time I receive the keypress ecent I reset the settimeout so that the total settimeout value is applied only when I stop receiving the keypress.

I have tried to follow examples in which is used the clearTimeout method but I do not see how to implement it in this case. How can I get this? Any idea.

greetings and thanks in advance for your time and help


Solution

  • i think what you are trying to achieve here is debouncing if i'm correct you can do it like this for every kry press we create a timeout and if the key not pressed for certain time the method in settimeout will be called

    var timeoutId = 0;
        function keypress() {
              if (timeoutId >= 0) {
                clearTimeout(timeoutId);
              }
              timeoutId = window.setTimeout(() => {
                callMethod();
              }, 500);// time to wait to listen for next keypress if not pressed callMethod will execute
            }