See LOL[1] to see how to implement state machines using closures.
Repeat, with JS closures.
[1] Let Over Lambda, Doug Hoyte https://letoverlambda.com/