javascriptnode.jstypescriptvue.js

Vue.js: Run a method after a delay, but reset the delay if user input happens


Suppose I have a form that is retrieving and displaying information from an API based on user input. As the user enters their query (for simplicity, let's say they are changing the number of results per page), the component should react and load the new data. I want to give the user a buffer zone - let's say, 2 seconds. If they enter their input, and 2 seconds passes without any new input, the component will perform an axios request. However, if more input is entered in that time, the 'timeout' will reset back to 2 seconds.

I feel like I would use a watched property to accomplish this but am struggling with the implementation. There's the obvious setTimeout method, but that won't allow me to reset the timer - I'd just call it multiple times with a 2 second delay.

How, using Vue.js, can I wait for user input, then wait for 2 seconds of inactivity (on that component), then perform an axios request?

Relevant Vue template:

<template>
    <input
        type="number"
        v-model.number="perPage" />    
</template>

Relevant Vue script:

<script>
    export default {
        data: function () {
            return {
                perPage: 25,
            }
        },
        methods: {
            myAxiosCall() {

            }
        }
    }
</script>

Solution

  • As you pointed out you are using setTimeout() method.

    Solution 1 -- Do this inside your text watcher

    save the result of setTimeout in a variable and use clearTimeout when you need to cancel. like this

    let x = setTimeout(functionName, time);
    //to clear -- when user starts typing clear the previously created timeouts
    clearTimeout(x);
    

    Solution 2

    Use debounce (import lodash). I find first one better. There may be many more approaches. Accept the answer if it helps.