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}/>
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}/>
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}/>
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.
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.
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}/>
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>