Have you thought about using a Finite State Machine (FSM) ?
It might be a bit of an overkill for what you are trying to do, but would seem to answer your requirement.
I created a write-up about FSMs on 'Share Your Projects' earlier this year.
Here's the link.
There's also a Node-RED node written by @cflurin that implements dynamic FSM.