How to run a function on input but with a delay with Vue.js and JavaScript?

Sometimes, we want to run a function on input but with a delay with Vue.js and JavaScript.

In this article, we’ll look at how to run a function on input but with a delay with Vue.js and JavaScript.

How to run a function on input but with a delay with Vue.js and JavaScript?

To run a function on input but with a delay with Vue.js and JavaScript, we can use setTimeout.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and the app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <div>
    	<input @input='onInput'>
      <div v-if='!isHidden'>hello</div>
    </div>
  `,
  data: {
    isHidden: true
  },
  methods: {
    onInput() {
      setTimeout(() => this.isHidden = false, 500);
    }
  }
})

to call onInput when the input event is triggered.

In onInput, we call setTimeout with a callback that sets this.isHidden to false to unhide the div after 500 milliseconds.

We use the v-if to only show the div with isHidden is false.

Conclusion

To run a function on input but with a delay with Vue.js and JavaScript, we can use setTimeout.