3
$\begingroup$

I would like to implement a "Stop" Button into a program that basically consists of a loop. Unfortunately I do not how to interrupt the running evaluation. Minimal Example:

Grid[{
{Button["Start", {i = 1; While[i < 10, Print[i]; Pause[1]; i++]}, 
Method -> "Queued"]},
{Button["Stop", {Quit[]}, Method -> "Queued"]}
}]

In this Case the "Stop" Button evaluates after the Evaluation from the "Start" Button has finished. Is there any possibility to quit the calculation immediately by a "Stop" Button? Thanks in advance for any Help!

$\endgroup$

1 Answer 1

5
$\begingroup$

From my perspective, the best way to interrupt a computation is with the menu command Evaluation/Abort Evaluation, or from the keyboard, as described here.

However, if using Button is desirable for other reasons, delete Method -> "Queued" so that the "Stop" code is executed immediately. Be aware, though, that Quit[] terminates the Kernel, losing definitions and the like; see its documentation. Instead, use Interrupt. In either case , Mathematica will stop responding for several seconds, then beginning responding again. With these changes, your code becomes

Grid[{{Button["Start", {i = 1; While[i < 10, Print[i]; Pause[1]; i++]}, 
    Method -> "Queued"]}, {Button["Stop", Interrupt[]]}}]

Note that Abort[] is ineffective in the code above.

Addendum

However, if the goal literally is to escape on command from a loop, like that in the test problem, Abort[], Break[], and a few other functions can be used, depending on the details of the loop. For instance,

Dynamic[break = False]
Grid[{{Button["Start", {i = 1; While[i < 10, If[break == True, Abort[]]; Print[i]; Pause[1]; 
  i++]}, Method -> "Queued"]}, {Button["Stop", Dynamic[break = True]]}}]

The advantage of this approach is that Mathematica does not temporarily become unresponsive when "Stop" is clicked. The disadvantage is that the loop terminates only where If[break == True, Abort[]] is encountered, although it can be located in multiple places in a large loop. Also, Dynamic can be temperamental.

$\endgroup$
2
  • $\begingroup$ Works perfect! Thanks a lot for your help! $\endgroup$
    – Peter
    Feb 17, 2015 at 13:17
  • $\begingroup$ Happy to help. I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$
    – bbgodfrey
    Feb 17, 2015 at 13:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.