Jagnesh Chawla
Jagnesh Chawla

Reputation: 892

What is the efficient way to hit api of Autocomplete text on keyup/keypress event in React / JavaScript?

We want to implement autocomplete input functionality with on keypress/keyup event, so that user can get auto suggestions from api. What will be the efficient way to hit api? We don't want to hit api on every keypress.

Upvotes: 1

Views: 1903

Answers (1)

Jagnesh Chawla
Jagnesh Chawla

Reputation: 892

Anyone can use this debounce and throttle functionality in WebApps and React native apps too. It's very useful while we want autocomplete Input text with api call.

Throttling

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval.

Debouncing

In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event.

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script type="text/javascript">
            function debounce(fn,d){
                let timer;
                return function(){
                    let context=this,
                    args=arguments
                    clearTimeout(timer);
                    timer=setTimeout(()=>{
                        fn.apply(context,args);
                    },d);
                }
            }


            function throttle(fn,d){
                let flag=true;
                return function(){
                    let context=this,
                    args=arguments
                    if(flag){
                        fn.apply(context,args);
                        flag=false;
                        setTimeout(()=>{
                            flag=true;
                        },d);
                    }
                }
            }

            let counter=0;

            let getData =()=>{
                console.log("Click :",counter++);
            }
            let autoCompleteText=(text)=>{
                console.log("AutoComplete :",text);
            }
            let deAutoCompleteText=debounce(autoCompleteText,300);
            let thGetData=throttle(getData,1000);

        </script>

    </head>
    <body>
    <input type="text" name="autotext" id="autotext" onkeyup="deAutoCompleteText(this.value)">
    <input type="button" value="Click Me" onclick="thGetData()">
    </body>
    </html>

Upvotes: 4

Related Questions