1

I have created functions that call other functions like

function abc()
{
    def();
}

function def()
{
    xyz();
}

Lets say def() is called and at any moment I have a button

<button>STOP</button>

if I press it the execution terminates that means if the execution is run again it should run again from start.

I have seen other solutions in SO but they show how to pause a loop. Can anyone help me out?

1
  • You can't stop an already-running function by clicking a button. The button click event won't be processed until the current JS execution finishes. Commented Apr 26, 2017 at 3:00

1 Answer 1

4

You could use a variable to determine whether your code runs or terminates:

var abort = false;

function abc()
{
    if (abort) {
        return;
    }

    def();
}

function def()
{
    if (abort) {
        return;
    }

    xyz();
}

<button onclick="abort = true">STOP</button>

The only thing you'd have to add is to reset abort back to false whenever you're triggering the main functionality.

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, but have in mind that depending on the way the function is coded, the UI could be blocked. While javascript runs certain stuff, like a for loop or something. So it is not that easy in most cases, imo
There is nothing in the way from UI
The OP seems to be asking how to press a button to stop a function that has already started executing. A flag won't help with that.
Jfren, the functions I have written are pretty long. Is there a way that an independent button stops the current on going execution of function?
@Alen, you could also sprinkle "if (abort) { return; }" throughout your function as well. I would say, though, that if you have really long functions, your code probably needs refactoring. You're kind of handicapping us here by not really telling us what problem you're trying to solve and abstracting it to fake examples. If you gave us the true problem you're trying to solve, we might be able to come up with a better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.