在 React / JavaScript 中点击 keyup/keypress 事件上自动完成文本的 api 的有效方法是什么?

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

我们想在 keypress/keyup 事件中实现自动完成输入功能,以便用户可以从 api 获得自动建议。命中 api 的有效方法是什么?我们不想在每次按键时都点击 api。

任何人都可以在 WebApps 和 React 本机应用程序中使用此 去抖和节流 功能。当我们想要使用 api 调用自动完成输入文本时,它非常有用。

节流

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.

去抖动

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>