Instant abortion functionality for an arbitrary function that takes time to execute?

19 Views Asked by At

I'm experiencing difficulty creating an "abortion function" for a looping function that takes significant time to execute, in JavaScript. My goal is to be able to have some stimulus (or one of a few different stimuli) immediately terminate the looping function and run some shutdown sequence instead. While I could obviously accomplish this by having conditional break/return statements all throughout the looping function that constantly check the abort condition(s), surely there must be a cleaner, easier-to-maintain way to accomplish this (async maybe)?

Below is some skeleton code to clarify the situation:

// Func() runs until some stimulus occurs, such as
// a key being pressed or a condition being met,
// after which it immediately stops in its tracks
// and Abort() runs instead

function Func() {
    while (true) {
        // Does a bunch of complicated stuff.
        // Probably calls other functions,
        // maybe has some Time.sleep() calls in there.
    }
}

function Abort() {
    // Shuts down whatever procedure was being performed
    // in Func() and terminates
}

I'm sure that the solution to this is simpler than I think, but I appreciate any input nevertheless!

0

There are 0 best solutions below