Home > database >  how to trigger a function after a delay only once with the latest value of the textbox
how to trigger a function after a delay only once with the latest value of the textbox

Time:06-21

I have react app & need to trigger a function once user stops typing in the textbox. This is what I tried.

const inputHandler =(e:SynthenticEvent) => {
 let timer: any = null;
 clearTimeout(timer);
 
 timer = setTimeout(() => {
 console.log('hi');
 //in actual sending an Http request, however hiding it here for brevity
},1000);
}

<input type="text" onChange={inputHandler} name="userInput" />

What's happening as of now, that the inputHandler trigger after 1000ms but it trigger the multiples times (ex 100 is triggering 3 times, 1000 triggers 4 times)

Which is not ideal or expected?

I thought to make use of useEffect, but on doing so inputHandler() is not in identified/scope by textbox?

What I'm looking is at trigger the function after 1000ms but once with latest value of the texbox?

Thanks!

CodePudding user response:

This called debounce

Debounce function.

function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  }
}

To use it.

const handleChange = debounce(() => console.log('hi'))


<input type="text" onChange={inputHandler} name="userInput" />

CodePudding user response:

You can use Loadash-Debounce for the same

Here's the article which will be helpful in this case.

codesandbox example

  • Related