So I am running a string reverse function. I have an input that console logs out whatever was typed into the input in reverse but now my problem is that when the text is being consoled out, it displays the letters one by one and I do not want that. I want it to return all the letters at once as a word. This is what my code looks like.
function Reduxy() {
const reverse = (str) => {
let reversedString = '';
setTimeout(() => {
for(var i = str.length-1; i >= 0; i--){
reversedString+=str[i];
}
console.log(`Reversed string ${reversedString}`);
}, 2000);
}
return (
<div>
<input type="text" placeholder='type word' onChange={e => reverse(e.target.value)} />
{/* <button onClick={}>Submit</button> */}
</div>
)
}
export default Reduxy
Where could I be going wrong?
It's currently writing the values to the console as you type them because the
onChangeevent is invoked with each change here.Based on this comment above, it sounds like you're not looking to respond to some future event but rather to implement a 2-second de-bounce window, in which the value is logged to the console only if the user has typed something and has stopped typing for 2 seconds.
In React I'd do this with a combination of
useStateanduseEffect. First you'd keep the value in state and all the input does is update that state. Every state update re-renders the component, anduseEffectwould make use of that by creating a 2-second timeout to display the value, and canceling that timeout any time the component re-renders.For example: