I have a function that does some animation using async await()
. I want to play/pause the animation onClick
. I used useState
to update the variable but the function is not behaving as I want. While the const print ()
is running and when I click on the button, text updates, but the function doesn't break. In the log, "play" is printed 100 times. I'm guessing useState
and async
is causing something. How can I solve this?
const Test= props => {
const [ButtonText, SetButtonText] = useState("Play");
const ToggleButtonText = () => {
if(ButtonText == "Play")
SetButtonText("Pause")
if(ButtonText == "Pause")
SetButtonText("Play")
}
const delay = ms => new Promise(res => setTimeout(res, ms));
const print= () => {
for(var i = 0; i < 100; i++)
{
///
work
await delay(1000);
work
///
console.log(ButtonText);
if(ButtonText == "Pause")
break ;
}
};
return (
<div>
<div>
///work component///
</div>
<button onClick = {() => ToggleButtonText()}> {ButtonText}</button>
</div>
)
}