-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
  • 93
  • 2
  • 7

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
  • 389
  • 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
  • 857,932
  • 118
  • 1,152
  • 1,264
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.

Geoman Yabes
  • 2,119
  • 2
  • 16
  • 38
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
  • 4,845
  • 2
  • 31
  • 29
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
  • 2,492
  • 1
  • 3
  • 7