skip to Main Content

I have a simple app. In my app I have an input and js function that performed if I write char in input. (every char).
Function wants a lot of time, may be 2 or 3 seconds it is ok. But I have a delay in input.
I make my function async and tryed this:

async function myFunction()  {
     ...//some long time job.
}

myInput.addEventListener('input', () => {
     myFunction().then(res => {
           //some job after function
     })
})

but I have a delay again. I’d like to see text in input straightaway.
What am I doing wrong?

2

Answers


  1. You are using a JavaScript function that performs a long task every time a character is entered in the input field, which seems to be causing a delay in input processing. Even when using an asynchronous function, calling myFunction every time an input event occurs can slow down the input handling. To solve this, you should use Debouncing. Debouncing is a technique where, instead of immediately executing the function every time an input event occurs, it waits until the user stops typing and then executes the function. Try debounce with the example code below.

       let timeout;
        
        function debounce(func, wait) {
            return function(...args) {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), wait);
            };
        }
        
        async function myFunction() {
            // ...
        }
        
        const debouncedMyFunction = debounce(() => {
            myFunction().then(res => {
                // ....
            });
        }, 300);
        
        myInput.addEventListener('input', debouncedMyFunction);
    
    Login or Signup to reply.
  2.   This How I will Do It.
    
    
    let timer = null;
    async function my function(){
                
    }
        
            myinput.addEventListener("change", ()=>{
                clear timeout(timer)
                setTimeout(()=>{
                  myfunction().then(()=>{
                  // do something
                  })
                }, 300)
            })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search