-1

I try do something when stop typing, I try this code but not working

const handler=(e)=>{
  let time;
  clearTimeout(time);
  time = setTimeout(() => {
     console.log("click");
  }, 2000);
}
<input onChange={handler}/>
just test
  • 273
  • 2
  • 4
  • 9

5 Answers5

2

I assume you want to cancel the timer if there is more input within 2 seconds. At present, your time variable is scoped to the handler function, so the value is lost when the function finishes executing.

Try using state to keep track of your timer:

const [timerID, setTimerID] = useState(null);
  
const handler = (e) => {
  clearTimeout(timerID);
  const id = setTimeout(() => console.log("click"), 2000);
  setTimerID(id)
}
  
return <input onChange={handler}/>
Steve Bunting
  • 419
  • 5
  • 12
0

The variable you store the timeout ID in needs to be defined outside the function, otherwise you get a new, undefined variable each time the handler is called.

That said, you are probably reinventing the wheel.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

time should be outside your function.

var time;
const handler = (cmp) => {
  clearTimeout(time);
  time = setTimeout(() => {
    console.log(`You typed ${cmp.value}`);
  }, 2000);
}
<input onChange="handler(this)" />

Also, 2 seconds seems a bit long.

xGeo
  • 2,149
  • 2
  • 18
  • 39
0

I know there's a better way of doing it but for now try this.

const [typing, setTyping] = useState(true)
useEffect(() =>{
if(! typing){
console.log("stop typing")
} 
}, [typing] ) 
const handleKeyUp =() =>{
   setTyping(true) 
     setTimeout(()=>{
       setTyping(false) 
}, 100) 
} 
<input onChange={handler} onKeyup={handleKeyUp}/>
crispengari
  • 7,901
  • 7
  • 45
  • 53
0

You can use a ref to keep track of the timer. This should keep the reference over re-renders and not cause additional re-renders of the component.

const Typing = () => {
  const timer = React.useRef();
  
  const handler = (e) => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
       console.log("Typed: " + e.target.value);
    }, 2000);
  }
  
  return <input onChange={handler} />;
};

const App = () => <Typing />;
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
Ben Stephens
  • 3,303
  • 1
  • 4
  • 8