You can use something called coroutines. Coroutines are basically threads, but they don’t run in parallel, they run when they are given a certain signal and stops when they yield. To use coroutines in javascript you must create something called generator functions. That way you can stop execution midcode and resume when you need to again. Note that this might have implications when running async functions.